text:
Q: wrap_content doesn`t work with background There is Frame Layout, where width\height = wrap_content. But it increases to max size when I try to set a background, even if it doesn't contains any elements.How to fix it?
<FrameLayout
    xmlns:android="schemas.android.com/apk/res/android";
   xmlns:app="schemas.android.com/apk/res-auto";
   android:background="@drawable/oblakol"
   adroid:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentTop="true"
   android:layout_centerInParent="true" >
    <TextView
      android:id="@+id/textView8"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="TextView" />
 </FrameLayout>

A: Your background is much bigger than you think. Check size of background!

A: Wrap content is working but your image size is large and hence you are not getting the expected results.
Try importing image as -> IMAGE ASSET so the size will be auto-Adjusted
or
set size manually!

A: I hope this will help you ...
wrap_content will put the background of it's original size.
Using large resolutions will cause lagging in your app while using. So, you should resize your background according to your needs : Image Resizer

A: When you set the dimensions(layout_width or layout_height) of a view to WRAP_CONTENT, you are giving freedom to the view to expand without any limit(as per its content ). Same is with your scenario as you've set the height and width to WRAP_CONTENT for your Frame Layout.
So whatever the space occupied on screen, its due to the large size of your android:background="@drawable/oblakol" drawable image. Try setting the height and width of the Frame Layout to some random values to test it.
android:layout_width="250dp"
android:layout_height="250dp"

I've attached some screenshots for your reference.

*

*android:layout_width and android:layout_height set to WRAP_CONTENT. Actual dimension of the android Image is 800x799(wxh)

*android:layout_width and android:layout_height set to WRAP_CONTENT. Actual dimension of the android Image is 256x256(wxh)

*android:layout_width and android:layout_height set to 250dp. Actual dimension of the android Image is 800x799(wxh)

Hope it helps.


text:
Q: Fix Text in , prevent moving after calculation Problem: I have 2 divs in a td-Tag, where the Text inside is moving positions, but shouldn't.
Div Code:

Noch zu berechnen

Mehl

I update the data in the div-id="mehlSumme2" with jQuery and the text is moving afterwards.
I can't get the text in mehlSumme2 right-bound fixed and mehl left-bound fixed.
I tried the following:
       #mehlSumme2, #zuckerSumme2, #butterSumme2, #quarkSumme2, #fuellungButterSumme2, #fuellungZuckerSumme2, #eierSumme2, #bananenSumme2, #apfelSumme2 {
        text-align: inherit;
        font-size: 70%;
        display: inline;
        padding-right: 10px;
    }

    #mehl, #zucker, #butter, #quark, #fuellungButter, #fuellungZucker, #fuellungEier, #bananen, #apfel {
        text-align: inherit;
        font-size: 70%;
        display: inline;
        padding-left: 10px;
    }

But this doesn't get me any further.
Thanks for your help!

A: Your problem might be the text-align: inherit bit. This will, for #mehlSumme2 and #mehl, make them have the text alignment from the parent (td).
You also have padding-right on the element that needs to be right-aligned. And padding-left for the element that needs to be left-aligned. padding: left adds space on the left of the element, so it effectively pushes the contents to the right boundary. (Same for padding: right.) Maybe if you switch them, you can make it look like what you want at least.
Another attempt would be adding text-align with :left or :right for those corresponding elements. Although, text-align is not very widely used since flex-box. And s are not widely used either.
EDIT: I added inline-block to your display property in the all the ids that have 2 after after them. It seems to not make the changing section shrink. Also, the code you posted did not work for the jQ. You just forgot to close the function properly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display Text Over Hover in Bootstrap I'm trying to add text on hover over an image inside a row and col-md-3. I want it to change opacity to set ideal while displaying text in centered inside the image.
I have the opacity hover down but I'm struggling with the data-hover class and I have no clue where to place the text I want inside HTML and CSS
I've included a fiddle here with all the work I have accomplished thus far: https://jsfiddle.net/a8u05mw1/
HTML:

  </div

CSS:
#wrapper img {
width: 100%;
transition-duration: 0.8s;
}

.col-md-3 {
padding: 0;
}

#wrapper img:hover {
opacity: 0.8;
transition-duration: 0.8s;
}

A: Answer 1: Without Bootstrap
jsfiddle answer 1

Your text here

Your text here

Your text here

Note: I removed the image which is no more available.
.container {
  position: relative;
  text-align: center;
  color: white;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* original example from question */
.img-responsive:hover + .img-hover-text {
  display: block;
}

.img-hover-text:hover {
  /* needed for the text to stay visible
  when the cursor it just over it.
  */
  display: block;
}

.img-hover-text {
  display: none;
  color: white;
  font-size: 20px;
}

Answer 2: With Bootstrap
jsfiddle answer 2
I made a new example inspired with your code, but using tooltips from Booststrap / Popper.js. I used the bootstrap starter template to quickstart the use of Boostrap.
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Hello, world!</title>

Hello, world!

Your text here

    <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top" title="Tooltip on top">
      Tooltip on top
    </button>

body {
  padding: 20px;
}

.img-container {
    position: relative;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.img-responsive:hover + .img-hover-text {
  display: block;
}

.img-hover-text:hover {
  /* needed for the text to stay visible
  when the cursor it just over it.
  */
  display: block;
}

.img-hover-text {
  display: none;
  color: white;
  font-size: 20px;
}

// Enable tooltip everywhere
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

Explaining Answer 1:
You want two things:

*

*First, center some text over an image.

*Then, apply a hover effect on the text so that it only appears when the cursor is hovering the image.

You can get a cool tutorial on how to center text over an image here | w3school.

Centered

.container {
  position: relative;
  text-align: center;
  color: white;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

This will give you the following picture:

Warning: Don't be like me. Don't waste your time on a
. Use a
 for the text directly.

Not Centered

Otherwise you will see this:

Ok, now we have our centered text. Time to make it disappear. Let's go back to your code and modify it.

Your text here

.img-responsive:hover + .img-hover-text {
  display: block;
}

.img-hover-text {
  display: none;
  color: white;
  font-size: 20px;
}

However, if we stop there, something will be wrong. When we hover the cursor right on top of the text area, the text disappear! To correct that, add a last css rule:
/* needed for the text to stay visible
  when the cursor it just over it. */
.img-hover-text:hover {
  display: block;
}

Explaining answer 2
The idea is not to do the stuff we made by hand, by using a library: namely Popper.js which fortunately is used by Boostrap. We include the tooltip with data-toggle="tooltip" data-placement="auto" title="This is a Tooltip" inside the element we want to display the tooltip on hover. Here inside .
To make is works, we also need to import the necessary library. Don't forget the  at the end, just before closing  flag.
Done!

A: Long story short for those looking for a Boostrap answer.
Add a tooltip in the flag you want.

// Enable tooltip everywhere
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

Don't forget to add Popper.js which is needed for the tooltip.


text:
Q: "ubuntu" shows up in boot menu, but my laptop keep telling me that "No OS detected" I tried to intall ubuntu 13.10 on my Acer Aspire 4750 yesterday, and I think I make a mistake choosing that "LVM" option.
Now I am facing these :

*

*"ubuntu" option now shows up in my boot menu. What is that? Why is it there? I have install ubuntu before on another notebook, but I never saw that before.

*How can I remove it or at least make my notebook boot ubuntu automatically? I can`t boot ubuntu without selecting that first on boot menu. And I have to access boot menu by pressing F12 when booting.

I have tried to reinstall it, but it still there.
This is my : Boot-Repair pastebin : http://paste.ubuntu.com/6931555/

A: That photograph is from your BIOS boot media menu. It detects some device - USB stick, another hard disk, or something - with name "ubuntu" on it. It says No OS detected, as that is not your hard disk.
You should choose "HDD 0: WDC..." option, if you installed the Ubuntu to your hard disk.

A: I am guessing you don't have any personal data on the laptop, right?
If this is the case, boot from ubuntu live cd or usb and select "Try Ubuntu". Once Ubuntu 13.10 loads, click on the Dash menu, and type "disks". Right Click on the computer's HD and chose "delete partition". Once it's done, close the disks app and go to your live cd's/usb's desktop. Click on the "Install Ubuntu" option and an the 3rd screen of the installation (the one where we chose the HD we want the OS to be installed) your first choice will be "Erase disk and install Ubuntu".
This will basically format your disk and install Ubuntu properly, leaving the essential spaces (like swap and boot load). (If you chose disk for installation manually you had to leave swap space and boot loader space on the HD).
Please let me know about any queries there might come up :)

A: I ran into a similar problem and I fixed it:
Main -> Network Boot -> F12 Boot Menu: [Enabled]
Save & exit
On next startup, hit F12, and I was presented with Windows or Ubuntu. Selected Ubuntu and it started right up.


text:
Q: The logic of the vscode custom link jump cannot open the link
I found two related APIs, go to define and custom editor, but so far testing go to define doesn't seem to work for markdown links (of known type), maybe go to define doesn't support blocking links and supports code level jumping?

*

*https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition

*https://code.visualstudio.com/api/extension-guides/custom-editors
The code is as follows
  vscode.languages.registerDefinitionProvider(
    {
      scheme: 'file',
      language: 'markdown',
      pattern: 'edit-*.md',
    },
    new JoplinMarkdownProvider(),
  )

export class JoplinMarkdownProvider implements DefinitionProvider {
  provideDefinition(
    document: TextDocument,
    position: Position,
    token: CancellationToken,
  ): ProviderResult<Definition | DefinitionLink[]> {
    console.log('provideDefinition: ', document, position, token)
    return undefined
  }
}

Update, registerDefinitionProvider can intercept clicks, but the returned Uri cannot be opened
For example, https://github.com/ will cause an error when opening
Unable to open'': Unable to resolve resource https://github.com/.

In addition, the query part of the custom schema link will be escaped
The shape is like vscode://rxliuli.joplin-vscode-plugin/open?id=03c8b00ed350410baf41c33daddf3005 => vscode://rxliuli.joplin-vscode-plugin/open?id%3D03c8b00ed350410baf41c33daddf3005
It will also report an error
Unable to open'open': Unable to resolve text model content for resource vscode://rxliuli.joplin-vscode-plugin/open?id%3D03c8b00ed350410baf41c33daddf3005.

The specific error code is at: https://github.com/rxliuli/joplin-vscode-plugin/blob/12854b05da7901a8655f69c90b65f56b67acc73f/src/extension.ts#L147

ref link: https://github.com/Microsoft/vscode/issues/8466


text:
Q: Access host network from container i got a service running on another machine on the same network, and i want my docker to access it's API
It's not an option to dockerize this service, so
Is there a way to give this docker full access to the network ? Or at least this machine and it's coresponding port


text:
Q: What is the complete set of representatives of an equivalence class? I have been researching the topic, but I can't find anything that explains specifically and in detail what it is. I just find a bunch of exercises about the topic.

A: When you have an equivalence relation defined on a set $S$, you partition the set into equivalence classes.
A representative of an equivalence class is any element of $S$ which belongs to that equivalence class. A complete set of representatives $R$ is a list of elements of $S$ such that you have a representative for each class. That is to say that any element of $S$ will be equivalent to exactly one element of $R$.
For example, if we take $S=\mathbb{Z}$ and define our equivalence as $a\sim b$ if $3|(a-b)$. This is the same as saying $a\sim b$ if $a\equiv b \mod{3}$. We can then take $R=\{0,1,2\}$ as given any integer $x$, either $x=3k$, $x=3k+1$ or $x=3k+2$ for some integer $k$ and hence $x$ will lie in the equivalence class of $0,1$ or $2$ respectively. Furthermore, these classes are all distinct so we have a complete set of representatives.
Finally, I just want to say that the set of representatives is by no means unique since we could have also taken $R$ to be $\{1,2,3\}$ or even $\{-1,6,52\}$.


text:
Q: Why does ASM.js have no annotations for unsigned? As titled,
From the specification, it seems I can make sure a value (x) could be evaluated to unsigned only by things like that: x >>> 0. But as I know, here the ">>>" should be an operator rather that annotation. So, why does ASM.js have no annotation for unsigned?
http://asmjs.org/spec/latest/#annotations
Besides, as we know, type "int" should be signed by default in programming languages like C and C++, but why the same type "int" has no signedness in ASM.js?
What the specification says as below, but I do not quite get the point.

The int type is the type of 32-bit integers where the signedness is not known. In asm.js, the type of a variable never has a known signedness. This allows them to be compiled as 32-bit integer registers and memory words. However, this representation creates an overlap between signed and unsigned numbers that causes an ambiguity in determining which JavaScript number they represent. For example, the bit pattern 0xffffffff could represent 4294967295 or -1, depending on the signedness. For this reason, values of the int type are disallowed from escaping into external (non-asm.js) JavaScript code.


text:
Q: JPA search query using Criteria Builder for multiple columns I am trying to make a universal search for my entity with criteria builder where a given text is matched with all the columns in the entity.
String likeSearchText = "%" + searchText + "%";
List<Customer> searchedCustomers = null;
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery(Customer.class);
Root <Customer> root = query.from(Customer.class);
ArrayList<Predicate> conditions = new ArrayList<>();
conditions.add(builder.like(root.<String>get("firstName"), likeSearchText));
conditions.add(builder.like(root.<String>get("lastName"), likeSearchText));
conditions.add(builder.like(root.<String>get("middleName"), likeSearchText));
conditions.add(builder.like(root.<String>get("companyName"), likeSearchText));
conditions.add(builder.like(root.<String>get("industry"), likeSearchText));
query.where(builder.or(conditions.toArray(new Predicate[conditions.size()])));
query.select(root);
searchedCustomers = entityManager.createQuery(query).getResultList();
return searchedCustomers;

When I run this method I always get an empty list. I tried changing the like to notLike and that works perfectly fine by giving me a list containing elements which are not like the given search text so I am really confused as to what's wrong with my like method.
Any kind of help would be appreciated!

A: I had similar problems when I made some testing and had entities with the same (simple)name in the classpath. So for example there were entities like:
org.example.one.Customer
org.example.two.Customer

If you do not have explicitly set different table names like:
package org.example.one;
@Entity("customer_one")
public class Customer { ...

and
package org.example.two;
@Entity("customer_two")
public class Customer { ...

hibernate might:

*

*mix stuff in the same table in db

*try to find field from wrong table when constructing the query

Also I thibk you do not need this:
query.select(root);


text:
Q: assigning value to React element onClick and passing as props I can not figure out how to assign a value to Raect element and pass it to state as props after clicking. The code is:
const mapDispatchToProps = (dispatch) => {
    return {
        contributionValue: (e) => dispatch(selectType(e.target.value))
    }
}

and the render part is
render() {
        return(
            <Container>
                <Option1 value='single' onClick={this.props.contributionValue}>
                    <Image src={Icon1}/>
                    <Text>Chcem finančne prispieť konkrétnemu útulku</Text>
                </Option1>
                <Option2 value='whole' onClick={this.props.contributionValue}>
                    <Image src={Icon2}/>
                    <Text>Chcem finančne prispieť celej nadácii</Text>
                </Option2>
            </Container>
        )
    }

My target value is always undefined, dont know how to set and assign this value (or any value for that matter) after clicking on element. Apparently the value I have set for each element is not being passed when clicked. I need storing single or whole to contributionValue based on which one is clicked.
Any ideas?


text:
Q: Inductive hypothesis of constructive induction Let $\Sigma$ be an alphabet and $\Sigma^*$ its Kleene closure (the set of all possible finite strings over the alphabet). Also, define the set of prefixes of $x \in \Sigma^*$ by
$$
\mathrm{pre}(x) = \{x[1:i] \mid i \in \{1, \ldots, |x|\}\},
$$
where the left associative subslice operator $[m:n]$ indexes into $x$, producing the substring between the indices $m$ and $n$ of the letters in $x$.
Show by constructive induction, that for all $x, y \in \Sigma^*$, if $x \in \mathrm{pre}(y)$, then then the length of the string $|x| \leq |y|$.
An attempt
The base case is easy. The empty string $\epsilon \in \mathrm{pre}(x)$ for all $x \in \Sigma^*$, and $|\epsilon| = 0 \leq |x|$ for all strings $x \in \Sigma^*$. Therefore our base case is valid.
Assume then, that $x, y \in \Sigma^*$, so that $|x| \leq |y|$. But then what? What am I actually supposed to induce? Should I vary the lengths of both $x$ and $y$ in the induction step or what?
I guess I'm asking, what is constructive induction really, and how is it different from weak induction? In weak induction we try to show that if the claim holds for a previous element, then it holds for the following element. In strong induction we assume that the claim holds for all previous elements and deduce that it has to hold for the next element.
But what is the inductve hypothesies in the case of constructive induction?
Edit
The question also has a second part: prove $|xy| + |x| + |y|$. I guess this is where I'm actually supposed to use induction. It's just the question was presented in a way that made me think induction was necessary even in the first part.
Still, my question is still unanswered. What is the inductive hypothesis (in general) when dealing with constructive induction?


text:
Q: How can I save an image with text overlaying it to the Gallery in Android Studio? We are trying to make an app that lets the user upload an image, write text over it, and then save the new image with the text.
Our current implementation is to use an ImageView to hold the image, then use TextViews to write on top of it.
What would be the best way to save the image as a whole? Below is our current code.
Thanks for the help! :)
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_generator);

    final EditText topTextInput = (EditText)findViewById(R.id.editTopText);
    final EditText bottomTextInput = (EditText)findViewById(R.id.editBottomText);
    final TextView topTextView = (TextView)findViewById(R.id.topText);
    final TextView bottomTextView = (TextView)findViewById(R.id.bottomText);

    imageView = (ImageView)findViewById(R.id.imageView2);
    Button pickImage = (Button) findViewById(R.id.button2);

    pickImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, SELECT_PHOTO);
        }
    });

    topTextInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            topTextView.setText(topTextInput.getText() + "");
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

    bottomTextInput.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            bottomTextView.setText(bottomTextInput.getText() + "");
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    switch(requestCode) {
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK){
                try {
                    final Uri imageUri = imageReturnedIntent.getData();
                    final InputStream imageStream = getContentResolver().openInputStream(imageUri);
                    final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                    imageView.setImageBitmap(selectedImage);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
    }
}

A: use this:
  public Bitmap takeScreenshot() {
        View rootView = getView();
        rootView.setDrawingCacheEnabled(true);
        rootView.buildDrawingCache(true);
        Bitmap b1 = Bitmap.createBitmap(rootView.getDrawingCache(true));
        rootView.setDrawingCacheEnabled(false); // clear drawing cache
        return b1;
    }

and to save the bitmap to image:
public void saveBitmap(Bitmap bitmap) {
    if(bitmap==null){
        return;
    }
    File imagePath1 = new File(savePath,"screenshot.jpg");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath1);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}


text:
Q: Get All Dates of Given Month and Year in SQL Server I want to get all dates by declaring month and year in SQL server.
Can anyone please share easy lines of SQL code to get it.
For example:
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016
SELECT * from Something

I have tried below things,
DECLARE @month TINYINT=5

;WITH CTE_Days AS (
    SELECT DATEADD(
               MONTH,
               @month,
               DATEADD(
                   MONTH,
                   -MONTH(GETDATE()),
                   DATEADD(
                       DAY,
                       -DAY(GETDATE()) + 1,
                       CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
                   )
               )
           ) Dates
    UNION ALL
    SELECT DATEADD(DAY, 1, Dates)
    FROM   CTE_Days
    WHERE  Dates < DATEADD(
               DAY,
               -1,
               DATEADD(
                   MONTH,
                   1,
                   DATEADD(
                       MONTH,
                       @month,
                       DATEADD(
                           MONTH,
                           -MONTH(GETDATE()),
                           DATEADD(
                               DAY,
                               -DAY(GETDATE()) + 1,
                               CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
                           )
                       )
                   )
               )
           )
)
SELECT Dates
FROM   CTE_Days

But I am looking for easy solution with less lines and short answer

A: Another CTE based version
DECLARE @Month INT = 2, @Year INT = 2019

;WITH MonthDays_CTE(DayNum)
AS
(
SELECT DATEFROMPARTS(@Year, @Month, 1) AS DayNum
UNION ALL
SELECT DATEADD(DAY, 1, DayNum)
  FROM MonthDays_CTE
  WHERE DayNum < EOMONTH(DATEFROMPARTS(@Year, @Month, 1))
)
SELECT *
  FROM MonthDays_CTE

A: If you have a date/time column, then use the month() function:
select t.*
from t
where month(datecol) = 5;

A: Same approach as t-clausen, but a more compact:
Declare @year int = 2017, @month int = 11;
WITH numbers
as
(
    Select 1 as value
    UNion ALL
    Select value + 1 from numbers
    where value + 1 <= Day(EOMONTH(datefromparts(@year,@month,1)))
)
SELECT datefromparts(@year,@month,numbers.value) Datum FROM numbers

A: You can't get all days just by declaring the month, you need to add the year as well because of leap years:
DECLARE @date DATE = getdate()

;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT top(day(EOMONTH(@date)))
  N day,
  dateadd(d,N-1, @date) date
FROM tally

Another different solution(by t@clausen):
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016

;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT N day,datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))

A: You can get all the dates of a month using the following query.
declare @month int, @year int
set @month = 2
set @year = 2008

SELECT
CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number
FROM master..spt_values
WHERE type = 'P'
AND
(CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number )
<
DATEADD(mm,1,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) )

Hope this will help you.

A: This is a other ways but same results.
declare @year int=2021,@month int=3

select  DATEADD(dd,a.n-1,datefromparts(@year,@month,1))
from    (
         select top 31 ROW_NUMBER() over (order by a.object_id) as n
         from   sys.all_objects a
      ) a where DATEPART(mm,DATEADD(dd,a.n-1,datefromparts(@year,@month,1)))=3

A: DECLARE @MonthNo TINYINT = 03 -- set your month
    ,@WOYEAR SMALLINT = 2018; -- set your year

IF OBJECT_ID('TEMPDB..#TMP') IS NOT NULL
    DROP TABLE #TMP

DECLARE @START_DATE DATETIME
    ,@END_DATE DATETIME
    ,@CUR_DATE DATETIME

SET @START_DATE = DATEADD(month, @MonthNo - 1, DATEADD(year, @WOYEAR - 1900, 0))
SET @END_DATE = DATEADD(day, - 1, DATEADD(month, @MonthNo, DATEADD(year, @WOYEAR - 1900, 0)))
SET @CUR_DATE = @START_DATE

CREATE TABLE #TMP (
    WEEKDAY VARCHAR(10)
    ,DATE INT
    ,MONTH VARCHAR(10)
    ,YEAR INT
    ,dates VARCHAR(25)
    )

WHILE @CUR_DATE <= @END_DATE
BEGIN
    INSERT INTO #TMP
    SELECT DATENAME(DW, @CUR_DATE)
        ,DATEPART(DAY, @CUR_DATE)
        ,DATENAME(MONTH, @CUR_DATE)
        ,DATEPART(YEAR, @CUR_DATE)
        ,REPLACE(CONVERT(VARCHAR(9), @CUR_DATE, 6), ' ', '-')

    SET @CUR_DATE = DATEADD(DD, 1, @CUR_DATE)
END

SELECT *
FROM #TMP

A: DECLARE @Today DATE= GETDATE() ,
@StartOfMonth DATE ,
@EndOfMonth DATE;

DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
SET @EndOfMonth = EOMONTH(GETDATE());
SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);

WHILE @StartOfMonth <= @EndOfMonth
BEGIN
   INSERT  INTO @DateList
   VALUES  ( @StartOfMonth );
   SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
END;

SELECT  DateLabel
FROM    @DateList;

A: WHERE Dates LIKE '2018-12%'

In a datetime or timestamp it goes Year-Month, so this would pull everything that matches 2018 in December. You can mod this to use your variables as well.
@month = 12;
@year = 2018;
@searchQuery = @year + @month + '%';

WHERE Dates LIKE @searchQuery

A: Little modification. Query given by @t-clausen.dk will give you correct result only if you ran it on first of the month. With little change this works awesome.
DECLARE @date DATE = getdate()

;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)

SELECT top(day(EOMONTH(@date)))
 N day,
 DATEFROMPARTS(year(@date),month(@date), n) date
FROM tally

BTW nice trick t-clausen.dk. I couldn't think of more easy way

A: Here is a query:
DECLARE @ReportDate VARCHAR(20)='2019-02-10'

DECLARE @LastDay INT =DAY(EOMONTH(@ReportDate))

DECLARE @DayStart INT=01

CREATE TABLE #TEMPMonth ([MDay] VARCHAR(20))

WHILE @LastDay>=@DayStart

BEGIN

INSERT INTO #TEMPMonth

SELECT CAST(CAST(YEAR(@ReportDate)AS VARCHAR)+'-'+CAST(MONTH(@ReportDate)AS VARCHAR)+'-'+CAST(@DayStart AS VARCHAR) AS DATE)
    SET @DayStart+=1

END

SELECT * FROM #TEMPMonth

DROP TABLE #TEMPMonth

A: CREATE FUNCTION fn_GetMonthlyDates
(
  @ProcessDate smalldatetime
)
RETURNS @LOAN TABLE
(
 ProcessDate    smalldatetime
)
AS
BEGIN
    DECLARE
        @Today DATE= @ProcessDate,
        @StartOfMonth DATE ,
        @EndOfMonth DATE;

    DECLARE @DateList TABLE (DateLabel VARCHAR(10) );
    SET @EndOfMonth = EOMONTH(@Today);
    SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);

    WHILE @StartOfMonth <= @EndOfMonth
    BEGIN
       INSERT  INTO @DateList
       VALUES  (@StartOfMonth );
       SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
    END;

    INSERT INTO @LOAN(ProcessDate)
    SELECT  DateLabel
    FROM    @DateList;

RETURN
END

A: A date list table won't take up my storage, will be more efficient than regularly run queries/functions and can be utilised elsewhere.
Create table and populate with all the dates you will need for the application's lifetime:
CREATE TABLE [dbo].[DateTable](
  [Date] [smalldatetime] NOT NULL PRIMARY KEY
, [Year] as year([Date]) PERSISTED NOT NULL
, [Month] as month([Date]) PERSISTED NOT NULL
, [Day] as day([Date]) PERSISTED NOT NULL);

Populate the table:
WITH DT
AS
(
  SELECT CAST('20000101' as datetime) AS [date]
  UNION ALL
  SELECT DATEADD(dd, 1, [date])
  FROM DT
  WHERE DATEADD(dd, 1, [date]) <= '20501231'
)
INSERT INTO DateTable
SELECT [date] FROM DT
OPTION (MAXRECURSION 0);

Non-Clustered Index:
CREATE NONCLUSTERED INDEX [IX_DateTable_Year_Month_inc_Date] ON [dbo].[DateTable]
(
    [Year] ASC,
    [Month] ASC
)
INCLUDE([Date])

Use will be simple and efficient from the non-clustered index:
select [Date]
from DateTable
where [Year] = @year and [Month] = @Month

A: I think the easier way to do that is something like this.
 Declare @date datetime ='20240301'
SELECT CONVERT(DATE, right('0'+convert(varchar,dia),2) +'/'+Right('0'+convert(varchar,Month(@date)),2)+'/'+convert(varchar,year(@date)),103)
    FROM (select value as dia from String_split('1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,',',')) T0
    WHERE T0.dia <= day(EOMONTH(@date))
    and isnull(dia,'')!=''

A: -- Another simple version:
DECLARE
@ADate DATETIME = '2022-03-01'
DECLARE
@Numberofdays INT =  (SELECT DAY(EOMONTH(@ADate)))
, @i int = 0
while @i < @Numberofdays
begin
print CONVERT(varchar(8), dateadd(day, @i, @ADate ), 112)
set @i= @i+1
end


text:
Q: Build jar and run spring boot from cmd I'm new to springboot and using springboot 2 version.
I would like to run my spring boot application using : java -jar my-app-0.0.1-SNAPSHOT.jar from the command prompt.
However, when i build the application using eclipse it calls myService.getMyMethod() directly and does not build the jar.
I want to build the jar file first and then run java -jar my-app-0.0.1-SNAPSHOT.jar from the command prompt which will invoke myService.getMyMethod()
I already have spring-boot-maven-plugin in pom.xml, running mvn package / mvn install starts the application but not generating the jar file in the target folder. mvn clean package also not working, MyApplication  is using implements CommandLineRunner and starts invoking the method on build, hence not generating the build jar file
My main class:
@SpringBootApplication
public class MyApplication implements CommandLineRunner {

private static String URL = "ws://localhost:8080/spring-mvc-java/chat";

   @Autowired
   private MyService myService;

   public static void main(String[] args) {
       SpringApplication.run(MyApplication.class, args);
   }
   @Override
   public void run(String... args) throws Exception {
       myService.getMyMethod(URL);
   }
}

My service class:
@Service
public class MyServiceImpl implements MyService {

     public void getMyMethod(String URL){
           WebSocketClient client = new StandardWebSocketClient();
           WebSocketStompClient stompClient = new WebSocketStompClient(client);
           stompClient.setMessageConverter(new MappingJackson2MessageConverter());
           StompSessionHandler sessionHandler = new MyStompSessionHandler();
           stompClient.connect(URL, sessionHandler);
           new Scanner(System.in).nextLine(); // Don't close immediately.
           }
}

A: In order to run the jar with java -jar you should use spring-boot-maven-plugin:
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.0.RELEASE</version>
            </plugin>
        </plugins>
    </build>

This plugin will "bake" all the dependencies of the project into the JAR and add some "technical" code that will allow to run this JAR with java -jar (the exact details are kind of out of scope for this question)
If you add it into the build, and run mvn package / mvn install it will create in the target folder a big JAR next to the original jar (that will be renamed with suffix .original).
You can open it with WinRAR/WinZIP and make sure that all your classes are there and all the dependencies are in BOOT-INF/lib folder.
Then you can run the project with java -jar

A: *

*In pom.xml add tag <packaging>jar</packaging>.

*you can build the maven project using command mvn package or maven install. It will create the .jar file inside target folder.

*run command from location where .jar is present - java -jar jarName.jar
Now you can access your system

A: Follow these steps

for eclipse/spring tool suite

*

*right click on project name to get these options --> Click on run as maven build

*Add Goal as package and click on Run button at bottom right corner

*jar file will be generated inside target folder of your project. You can locate this and then run java -jar command


text:
Q: Proving $| \text{Tr}[AB] | \leq \text{Tr}[ |AB| ]$ for $A,B \in \text{Pos}(V)$ I came across an inequality for (finite dimensional) positive semi-definite operators and I tried to prove it, but I falied. Therefore, I hope some of you have a hint for me, what I missed.
Before I start, I give the definition of what is meant by $|A| := \sqrt{A^*A}$, where $A^*$ is transposing the matix $A$ and taking the element-wise coplex conjugate.
As this question occurres in in connection with a physical problem I hope that it is ok to use Dirac's BraKet notation.
Suppose now $A,B \in \text{Pos(V)}$, where $V$ is some finite-dimensional vector space. I want to show that
$| \text{Tr}[AB] | \leq \text{Tr}[AB]  $
holds.
In my approach to prove this statement, I used that every positive operator is Hermitian and can be diagonalized, $A = \sum_i \lambda_i |v_i\rangle \langle v_i |$ and $B = \sum_j \mu_j | u_j \rangle \langle u_j |$, where $\{v_i\}$ and $\{u_j\}$ are bases, consisting of eigenvectors of $A$ and $B$, respectively.
Thus, one can rewrite
$|\text{Tr}[MN]| = | \sum_i \sum_j \lambda_i \mu_j |\langle v_i|u_j\rangle|^2|$.
Once I try to rewrite the right hand-side of the inequality in a similar way, it becomes a real mess, as I cannot assume that both $A$ and $B$ are diagonalized with respect to the same basis, hence I am left with lots of inner products between basis vectors from $\{v_i\}$ and $\{u_j\}$ (under the root, which occurrs due to the definition of the absolute value of a matrix - see above).
Is there any trick, how I can prove this statement directly, or is there anything that I missed when tying my "brute force diagonalizing" approach?
I am very grateful for any help!

A: Theorem.  For any matrix $A$,  one has that
$$
  |\text{tr}(A)|\leq \text{tr}(|A|).
  $$
Proof.
Considering the inner product  defined on $M_n(\mathbb C)$ by
$$
  \langle X, Y\rangle =\text{tr}(X^*Y),
  $$
one has
by the Cauchy-Schwartz inequality that
$$
  |\text{tr}(X^*Y)|\leq \text{tr}(X^*X)^{1/2}\text{tr}(Y^*Y)^{1/2}.
  $$
Using  the polar decomposition,  write $A=U|A|$, where $U$ is a unitary matrix, and set
$X=|A|^{1/2}U^*$, and $Y=|A|^{1/2}$.  Then $A=X^*Y$, so
$$
  |\text{tr}(A)|=|\text{tr}(X^*Y)| \leq
  \text{tr}(X^*X)^{1/2}\text{tr}(Y^*Y)^{1/2} =
    $$
$$ =
  \text{tr}(U|A|U^*)^{1/2}\text{tr}(|A|)^{1/2} = \text{tr}(|A|).
  $$

PS: The same proof can be used to show that $|\tau(A)|\leq \tau(|A|)$, for every positive trace $\tau$ on any $C^*$-algebra $\mathscr A$, that is, any linear functional
$$
\tau:\mathscr A \to \mathbb C,
$$
such that $\tau(A^*A)\geq 0$, and $\tau(BA)=\tau(AB)$, for every $A$ and $B$ in $\mathscr A$.


text:
Q: Regular Expression to get one field from otherwise constant pipe delimited string What is a regular expression for
initSock|north|router\r\n

Where there is north changes all the time but the rest is always the same.
So It can be:
initSock|foo|router\r\n
initSock|bar|router\r\n

etc.
But where north, foo or bar are there definitely should be something and can't be empty.
I am going to use this in C#.
To make it more clear:
Any thing that looks like this is bad:
initSock||router\r\n
initSockfoorouter\r\n
|foo|router\r\n
initSock|foo|router
initSock|foo|portal\r\n
outSock|foo|router\r\n

A: "^initSock\|([a-zA-Z]+)\|router\\r\\n$"

Although I would probably be tempted to split on the pipe ("|") character...

A: To extend the above answer from M Potato Head to allow for all possible characters I'd rewrite the regexp as:
"^initSock\|[^|]+\|router\\r\\n$"

or
"^initSock\|[^|][^|]*\|router\\r\\n$"

if you can't use extended regexp. That way you don't have to ensure that you've allowed for all possible chars in the set of characters that you're using to match the varying part of the name.
HTH
cheers,
Rob


text:
Q: Why hot observable resubscribe I have an observable that listen on table select event, it is also hot.
The code snippet:
  const oTableRowSelect$ = TableOb.rowSelectionChangeEvent$(this.getById("ins-table"));
  const test = oTableRowSelect$
    .do(function () {
      console.log("resubscribe");
    })
    .map(function () {
      return 4;
    });

  test.subscribe(function (o) {
    console.log("Select1" + o);
  });

  test.subscribe(function (o) {
    console.log("Select2" + o)
  });

As you can see, there are two subscribers, that listen on the event. So the result should share to all subscribers, that what is called a replay effect.
The output, that I've got is:

But I am expecting resubscribe output only once. What am I doing wrong?

A: While your oTableRowSelect$ might be hot and shared, it is only shared up the the part where you extend it somehow with additional operator(s) (in your case do and map).
In RxJS any extension through an operator will basically return a "new" stream.
In order to make this "new" stream hot/shared you'd have to apply an operator that makes it hot (share, publish, publishReplay, ect...)

const hotBaseStream$ = new Rx.BehaviorSubject("Hi!");

const test = hotBaseStream$
    // -------- below this line you get a "new" stream, that is not hot any more
    .do(() => console.log("resubscribe"))
    .map(() => 4)
    .publishReplay().refCount();  // remove this part and you will have back your original behavior

  test.subscribe(function (o) {
    console.log("Select1 ", o);
  });

  test.subscribe(function (o) {
    console.log("Select2 ", o)
  });
<script src="https://unpkg.com/@reactivex/rxjs/dist/global/Rx.js"></script>


text:
Q: Can't Get Variable into Jquery Function The percent variable gets "alerted" just fine.  But, when I put it in the progressbar function, just defaults to zero.  It will work if I hardcode the value i.e. value: 60.  How can I make it work with my percent variable?  Thanks.
    function updateProgress(percent)
    {
        alert(percent);
        $("#progressbar").progressbar({
            value: percent
        });
    }

A: The problem is that the variable percent is a string here so convert it to an integer or better a float:
value: parseFloat(percent)

A: function updateProgress (percent) {
  alert(percent);

  $("#progressbar").progressbar({
    value: parseFloat(percent)
  });
}

A: Your code looks correct. Try this:
function updateProgress(percent)
{
    var progress = {
        value: percent
    };
    alert(progress.value);
    $("#progressbar").progressbar(progress);
}


text:
Q: Uploading Large size File (in chunks) on Sharepoint using Web Services I want to upload upload up to 100 MB to 1GB file onto sharepoint using Web Services ( C#).
Which can only possible by passing file data into chunks.
Regards,
Jene

A: Try this code : http://geek.hubkey.com/2007/10/upload-file-to-sharepoint-document.html


text:
Q: How to use SSH to move a file from Ubuntu to Windows? I am logged onto a windows machine. I am using Putty to login to an Ubuntu machine on the same network. Now I'm trying to move a .c file from the Ubuntu machine, to the Windows machine, edit it there, then move it back to the Ubuntu machine, compile it, and run it.
I'm still stuck at obtaining the C file.
I'm running this command...
sudo scp odroid:/home/odroid/test/test.c C\Users\MyUser\Downloads

Instead of moving the file to my Windows machine...somehow I'm creating an un-extended file in the home directory of my Ubuntu machine.
What am I doing wrong?

A: In similar cases, I've used WinSCP.
It's a Windows SCP client that allows you to browse the Linux file system graphically and scp files back and forth between the 2 machines.
Available here :
http://winscp.net/eng/index.php

A: You're doing this the very hardest way, but here you go:

*

*Get the wonderful pscp program. I'm not a Windows person at all so all I can tell you is put pscp.exe in your %path%.

*On the Windows machine, change directory to C:\Users\MyUser\Downloads

*On the Windows machine: pscp test.c  odroid:test/  You'll probably have to type in your Ubuntu password.

*On the Ubuntu machine, compile and test.

You have to "pull" the file from your Linux machine, because Microsoft artificially makes computers into "servers" and "clients" (presumably to create false high price points for corporate buyers) and doesn't see fit to put a SSH server on anything.  For that matter, you may need to start sshd on your Ubuntu box.
Honestly, you'd be better off doing text editing on the Ubuntu machine. First, there's an amazing range of editors of various types available, from NotePad imitators to full-blown IDEs. Second, you're going to have problems with end-of-line bytes moving the file back-and-forth between Windows and Linux. At some point, the compiler will refuse to compile something, or your Windows editor won't recognize a single newline character as end-of-line.

A: I've had to deal with this a lot, and I used to teach a few classes where students needed to work from Windows machines. I'll describe two methods, and you decide what you like best. Also, warning: I am not a Windows user, I just provide support for them when they need to work with Unix :).

*

*Use WinSCP (http://winscp.net/eng/download.php)
WinSCP is just a GUI which works similarly to PuTTY, but you can browse files on the remote server. I've found it fairly acceptable, and it's a GUI so you can just drag and drop files/folders between your local Windows machine, and the remote Ubuntu Linux machine.

*Use Sublime Text 3 (https://www.sublimetext.com/3) along with the Sublime SFTP plugin (sorry, you'll have to search for this)
(Ok, I'm basically endorsing this one text editor, but ever since a friend of mine showed it to me, I've found it to be my preferred editor in most circumstances. Other editors might let you do something like this; please feel free to check them out. I'm sure everyone has their favorite.)
ST is paid software available on a trial basis, and will keep asking you to buy it every few times you save. You can safely ignore this forever and it doesn't cost you any functionality to use it for free, but just be aware of this (and if you can support the developers...). The SFTP plugin will also nag you to buy it.
This is how I use ST3 and the SFTP plugin (I assume you've already installed both).
If you're going to be working with all files in a remote folder

*

*Open ST3 and select File -> "Open Folder"

*Create a new folder, if you wish. This folder will hold all the files you need to work with. Otherwise, just select a folder.

*In the left sidebar, right click on the folder name or icon. Choose SFTP/FTP -> "Map to Remote".

*ST3 will open a config file for setting up your connection. Fill in the important values (host, user, remote_path). remote_path should be the directory that your local directory will be "mirroring" in a sense. You can also set upload_on_save to true if you want your files to be copied automatically to the remote server every time you save.

*Save the file and right-click on the folder name again. This time, pick SFTP/FTP -> "Sync Remote -> Local...". Warning: if the folder you picked has files in it, this will overwrite them.

*Select "Yes" when it asks to perform the operations shown in the console.

*Now your files will show up on the side bar. You can open them, edit them, and save them, all on you local machine. If you did not set the upload_on_save option, you can right click on the file name, or anywhere inside the file and pick SFTP/FTP -> "Sync Local -> Remote..." to copy it back.

If you're going to be working with just one file
It may be easier for you to just edit the file in Sublime Text, via the SFTP plugin. This gives you the feeling of working with it locally, but really, only a cached version of it exists on your local machine. The developer of the SFTP plugin calls this the "Server" workflow (you can read about it on their page). Basically:

*

*Open ST3, File -> SFTP/FTP -> "Set up server..."

*Fill in the config file, similarly to how I described above, and save it with a name (maybe the name of the server is a good idea).

*File -> SFTP/FTP -> "Browse remote..."

*Use the rather clunky interface to browse for your file, select it, then select "Edit"

*Edit your file as you wish. Saving uploads it automatically.

I found that ST3 works well enough for my needs. Hopefully this helps you at least somewhat. If you're not looking for another editor, hopefully WinSCP helps you do what you need to do.

A: ensure that you have the pscp first, use the git Bash instead of windows power shell, scp odroid:/home/odroid/test/test.c C\Users\MyUser\Downloads


text:
Q: Delete leading characters from multiple lines pls see the below example, I need to retain only those characters that are succedded by RA: on all the lines and i need to delete all values upto RA:
so for example
FP: 0x33A173D0, RA: 0x947BD1C should yield me 0x947BD1C  the pattern of these characters are usually the same, they begin with FP: ,two white spaces,followed by hex values and then a comma with two white space and then RA: I extremely new to regex since I do this repetively in my job someone suggested that I do this by regex but they did not know how.. and neither do I. so I am looking for help here
FP: 0x33A173D0, RA: 0x947BD1C
FP: 0x33A173F0, RA: 0x895AA8C
FP: 0x33A17400, RA: 0x8934DD0
FP: 0x33A17430, RA: 0xA3C6990
FP: 0x33A17438, RA: 0xA3C6C10
FP: 0x33A17448, RA: 0xA3C6F4C
FP: 0x33A17480, RA: 0xA68769C
FP: 0x33A17498, RA: 0xA8097A4
FP: 0x33A174F8, RA: 0x9DE4410
FP: 0x33A17528, RA: 0x8E01CD8
FP: 0x33A17548, RA: 0x8E02D1C
FP: 0x33A17560, RA: 0x8E0497C

A: Try with:
^(.*?RA: )

and replace matched group with empty string. Or match:
^.*?RA: (.*)$

to get your final content.

A: Python example:
result = re.sub(r"(?m)^.*,\s*RA:\s*", "", subject)

Explanation:
(?m)    # Multiline mode
^       # Match start of line
.*      # Match any number of characters
,\s*    # Match a comma, followed by optional whitespace
RA:\s*  # Match "RA:", followed by optional whitespace

A: I assume you are reading those values line by line, then you can use
.*RA:\s*(.*)$

and replace with
$1

See it here on Regexr

A: In your text editor that supports REGEX(such as vim, UltraEdit), find
FP: +0x[0-9A-F]+, +RA: +(0x[0-9A-F]+)

replace with
$1

or in some special editor(such as Crimson Editor, EditPlus) should replace with
\1


text:
Q: Terminating threads in Java with several requests? Suppose I have a method in a CLIENT Java application (ie Android app)
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool

public void makeHTTPRequestVeryVeryCostly() {
  /* IN A BACKGROUND THREAD */
   CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
   s.get();
   updateTheUserUIInTheMainUIThread(s); //Update with s
}

button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request

In anger, the user taps the button 100 times, then 100 requests have been submitted into the ThreadPool. 2 bad things occur:
(1) Costly request computed 100 times
(2) The UI is refreshed 100 times after each return.
These are all very big issues. In Java, what's the way of solving this? It would be best to terminate all preceeding requests in the thread pool after one sucessful request, how can this be done?

A: If you want send each http request, but no concurrency。 Lock may help you here. Below pseudo-code:
ExecutorService pool = ExecutorsService.newFixedThreadPool(1); //1 thread in pool
Lock httpRequestLock = new ReentrantLock();

public void makeHTTPRequestVeryVeryCostly() {
   boolean locked = httpRequestLock.tryLock(10, TimeUnit.SECONDS);
   if(!locked){
     //can't get the request lock util timeout(10s)
     return;
   }

   try{
      /* IN A BACKGROUND THREAD */
       CompleteableFuture<String> s = CompleteableFuture.supplyAsync(() -> makeCostlyReq, pool));
       s.get();
       updateTheUserUIInTheMainUIThread(s); //Update with s
   }finally{
       httpRequestLock.unlock();
   }
}

button.onClicklistener((b) -> makeHTTPRequestVeryVeryCostly()); // some button in the UI that will make the http request

We use a Lock to ensure only one request at same time, and set a timeout to follow-up request when get lock to send a request.
In addition, if you just want a user just send request in a low frequency,like 1 time/10s。You can declare a variable to keep last time the request sent, and every time check the duration between the last execute time and current time.


text:
Q: For $a>0$, $\displaystyle\int_{\arctan a}^{\frac{\pi}{2}}\int_{0}^{a\csc\theta}\frac{r}{(1+r^2)^2}\,dr\,d\theta=?$ I found an answer, $\displaystyle\int_{\arctan a}^{\frac{\pi}{2}}\int_{0}^{a\csc\theta}\frac{r}{(1+r^2)^2}\,dr\,d\theta=\frac{a}{2\sqrt{a^2+1}}\arctan\left(\frac{1}{\sqrt{a^2+1}}\right)$ for $a>0$.
But I am not sure how to get the result.
First of all, $\displaystyle\int_{0}^{a\csc\theta}\frac{r}{(1+r^2)^2}\,dr=-\frac{1}{2}\left(\frac{1}{1+a^2\csc^2\theta}-1\right)$ and using an integral calculator, $\displaystyle\int-\frac{1}{2}\left(\frac{1}{1+a^2\csc^2\theta}-1\right)\,d\theta=\frac{a}{2\sqrt{a^2+1}}\arctan\left(\frac{\sqrt{a^2+1}\tan \theta}{a}\right)+C$. But I can't evaluate $\tan \theta$ at $\theta=\frac{\pi}{2}$. How can I get to the answer above?

A: So, your second integral is
$$\frac{1}{2}\int_{\tan^{-1}a}^{\frac{\pi}{2}}\frac{a^2 \csc^2 \theta}{1 + a^2\csc^2\theta}d\theta$$
Multiplying the numerator and denominator by $\sin^2\theta$, you get
$$\frac{1}{2}\int_{\tan^{-1}a}^{\frac{\pi}{2}}\frac{a^2}{\sin^2\theta + a^2}d\theta$$
The next step is very generic for solving such integrals.
Hint: Divide both numerator and denominator by $\cos^2 \theta$. Should be doable after this. I will write the complete solution anyway, but you can skip from here and try solving on your own.
$$\frac{1}{2}\int_{\tan^{-1}a}^{\frac{\pi}{2}}\frac{a^2\sec^2
\theta}{\tan^2\theta + a^2\sec^2\theta}d\theta = \frac{1}{2}\int_{\tan^{-1}a}^{\frac{\pi}{2}}\frac{a^2\sec^2
\theta}{(a^2+1)\tan^2\theta + a^2}d\theta$$
Now, let $\tan \theta = x$, you get
$$\frac{1}{2}\int_a^\infty \frac{a^2}{(a^2+1)x^2+a^2}dx = \frac{a}{2\sqrt{a^2+1}} \left[\tan^{-1}\frac{\sqrt{a^2+1}}{a}x\right]_a^\infty$$
This gives us
$$\frac{1}{2}\int_{\tan^{-1}a}^{\frac{\pi}{2}}\frac{a^2 \csc^2 \theta}{1 + a^2\csc^2\theta}d\theta = \frac{a}{2\sqrt{a^2+1}}\left[\frac{\pi}{2} - \tan^{-1}\sqrt{a^2+1}\right] = \frac{a}{2\sqrt{a^2+1}} \tan^{-1}\frac{1}{\sqrt{a^2+1}}$$

A: HINTS:
Note that we have
$$\lim_{x\to \pi/2^-}\tan(x)=\infty$$
and
$$\lim_{x\to \infty}\arctan(x)=\pi/2$$
Finally, use $\pi/2 -\arctan(x)=\arctan(1/x)$ for $x>0$.


text:
Q: Objects are not valid as a react child (found : TypeError : filepath.includes is not a function) I ran into this problem when I tried using react-native-fetch-blob to  upload photos in firebase storage!
This is the code for uploading the file.
uploadImage = (uri, imageName, mime = 'image/jpg') => {
  return new Promise((resolve, reject) => {
    const uploadUri = uri
    let uploadBlob = null
    const imageRef = firebase.storage().ref('posts').child(imageName)
    fs.readFile(uploadUri, 'base64')
      .then((data) => {
        return Blob.build(data, { type: `${mime};BASE64` })
      })
      .then((blob) => {
        uploadBlob = blob
        return imageRef.put(blob, { contentType: mime })
      })
      .then(() => {
        uploadBlob.close()
        return imageRef.getDownloadURL()
      })
      .then((url) => {
        resolve(url)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

This is the code which calls the function uploadImage:
this.uploadImage(this.state.avatarUri.uri, userId).then((imageURL) => {
  saveDatabase(userId, imageURL)
}).catch((error) => {
  this.setState({
    error,
    isLoading: false
  })
})

The avatarUri is set from the imagepicker library as follows:
openCamera = () => {

  ImagePicker.launchImageLibrary({}, (response) => {
    if (response.didCancel) {

    } else if (response.error) {
      this.state.imageError = response.error
      console.log('ImagePicker Error: ', this.state.imageError);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      this.setState({
        avatarUri: {
          uri: response.uri
        },
        imgPath: response.imgPath,
        error: ''
      });
    }
  });

}

The error screenshot is here:

EDIT
Render Function is as following:
        this.state.isLoading ?
            <Spinner style={{flex:1, alignSelf: 'center'}} color='blue' />
        :
        <Container>
        <Content style={{margin:20}}>

            <Item>
                <Icon type="FontAwesome" active name='user' style={{ color :'#c5aa6a'}} />
                <Input
                    placeholder='Email'
                    onChangeText= { (text)=> { this.setEmailText(text) } }
                    value={this.state.email}/>
            </Item>

            <Item>
                <Icon type="FontAwesome" active name='key' style={{ color :'#c5aa6a'}} />
                <Input
                    secureTextEntry
                    placeholder='Password'
                    onChangeText= { (text)=> { this.setPasswordText(text) } }
                    value={this.state.password}
                    />
            </Item>

            <Item>
                <Icon type="FontAwesome" active name='key' style={{ color :'#c5aa6a'}} />
                <Input
                    secureTextEntry
                    placeholder='Confirm Password'
                    onChangeText= { (text)=> { this.setRePasswordText(text) } }
                    value={this.state.re_password}
                    />
            </Item>

            <Button bordered success  style={{ justifyContent: 'center', marginTop: 20}} onPress = { ()=> this.verifyCredentials() } >
                <Text style={{color:'#c5aa6a'}}>Sign Up</Text>
            </Button>

            {
                !this.state.avatarUri ?
                <Icon type="FontAwesome" active name='user-circle' style={styles.photoPicker} onPress= { ()=> this.openCamera() } /> :
                <Image style={styles.avatarPicked}  source= {  this.state.avatarUri }  />

            }

            {
                this.state.error ?
                    <Text style= {{ color: '#ff0000', alignSelf: 'center', marginTop: 30}}>    {this.state.error}  </Text>
                    :
                    null
            }

        </Content>

        <Button transparent onPress={() => this.props.navigation.navigate('login')} style={styles.buttonStyle} >
            <Text style={{color:'#c5aa6a'}}>I already have an account</Text>
        </Button>

        </Container>


text:
Q: General error: 1843 OCIStmtExecute: ORA-01843: not a valid month (ext\pdo_oci\oci_statement.c:148)' I am trying to insert to a oracle table using pdo. Its getting an error:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error: 1843 OCIStmtExecute: ORA-01843: not a
  valid month` (ext\pdo_oci\oci_statement.c:148)' in
  D:\xampp\htdocs\ipack\insertstatus.php:60 Stack trace: #0
  D:\xampp\htdocs\ipack\insertstatus.php(60): PDOStatement->execute() #1
  {main} thrown in D:\xampp\htdocs\ipack\insertstatus.php on line 60

This is my code:
$today = date("d-m-Y");
$stmt = $dbh->prepare("INSERT INTO PRTJOBSTATUS (INTJOBNO,SLNO,OPDATE,OPERTYPE,OPUSER,REMARKS,STATUSCODE,STATDATE)
    values (:intjn,:sn,:opdt,:optype,:opusr,:rmks,:stcd,:stdt)");
    $stmt->bindParam(':intjn',$intjobno);
    $stmt->bindParam(':sn',$slno);
    $stmt->bindParam(':opdt',$today);
    $stmt->bindParam(':optype',$optype);
    $stmt->bindParam(':opusr',$opuser);
    $stmt->bindParam(':rmks',$remarks);
    $stmt->bindParam(':stcd',$statuscode);
    $stmt->bindParam(':stdt',$today);
    if($stmt->execute()) {
      echo '1 row has been inserted';
    }
    $dbh = null;

A: You're inserting into a column "STATDATE". I would imagine this will be of type Date. Therefore you'll have to pass a date object into the insert statement.
Change your $today variable to return a string in the following format 'DD-MON-YYYY' eg 31-DEC-2015
Then change your insert statement to the following:
"INSERT INTO PRTJOBSTATUS (INTJOBNO,SLNO,OPDATE,OPERTYPE,OPUSER,REMARKS,STATUSCODE,STATDATE)
values (:intjn,:sn,:opdt,:optype,:opusr,:rmks,:stcd,TO_DATE(:stdt,'DD-MON-YYYY'))"


text:
Q: Get number of years with a date in ISO8601 I'm trying to get number of years since a date provided with a string in a "2013-12-06" format. I want to compare it to today (2020-21-06) and have the number of years that I can put in an int.
For exemple, I receive

String d = "2013-12-06"

Today's date is the 2020/21/06.
How do I get the difference beetween the two in years?
In this example it would be 6 years.
Thank you very much!

A: java.time.Year
import java.time.Year;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        Year year = Year.parse("2013-12-06", DateTimeFormatter.ISO_DATE);
        long years = year.until(Year.now(), ChronoUnit.YEARS);

        System.out.println(years);
    }
}

Output:
7

A: import java.time.LocalDate;
import java.lang.Math;
import java.lang.Integer;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LocalDate now = LocalDate.now();
        String nowTime = now.toString();
        String d = "2013-12-06";
        String year = d.substring(0, 4);
        String NowYear = nowTime.substring(0, 4);
        int yearInt = Integer.parseInt(year);
        int NowYearInt = Integer.parseInt(NowYear);

        int diff = NowYearInt - yearInt;
        System.out.println(diff);
    }

}

The old fashioned way. Prints 7. Works if the year is from 1000 - 2020.


text:
Q: Trying to load local JSON file to show data in a html page using JQuery Hi I am trying to load local JSON file using JQuery to show data but i am getting some weird error. May i know how to solve this.

I am just alerting the count of JSON data. My JSON file is in the same directory where this html file is and JSON string format is shown below.
{
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

JSON file name priorities.json and error is

Uncaught Referenceerror priorities is not defined

A: You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.
index.html:

data.js:
var data = {
  "start": {
    "count": "5",
    "title": "start",
    "priorities": [{
      "txt": "Work"
    }, {
      "txt": "Time Sense"
    }, {
      "txt": "Dicipline"
    }, {
      "txt": "Confidence"
    }, {
      "txt": "CrossFunctional"
    }]
  }
}

A: app.js
$("button").click( function() {
 $.getJSON( "article.json", function(obj) {
  $.each(obj, function(key, value) {
         $("ul").append("
"+value.name+"'s age is : "+value.age+"
");
  });
 });
});

index.html
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Tax Calulator</title>

    <button>Users</button>

article.json
{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}

server.js
var http = require('http');
var fs = require('fs');

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/') {
          response.writeHead(200,{"Content-Type":"text/html"});
          fs.createReadStream("./index.html").pipe(response);
  } else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
  } else if(request.method == 'GET' && request.url == '/app.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./app.js").pipe(response);
  }
  else if(request.method == 'GET' && request.url == '/article.json') {
          response.writeHead(200,{"Content-Type":"text/json"});
          fs.createReadStream("./article.json").pipe(response);
  }
}

http.createServer(onRequest).listen(2341);
console.log("Server is running ....");

Server.js will run a simple node http server in your local to process the data.
Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html
This is my running one https://github.com/surya4/jquery-json.

A: Due to security issues (same origin policy), javascript access to local files is restricted if without user interaction.
According to https://developer.mozilla.org/en-US/docs/Same-origin_policy_for_file:_URIs:

A file can read another file only if the parent directory of the
  originating file is an ancestor directory of the target file.

Imagine a situation when javascript from a website tries to steal your files anywhere in your system without you being aware of. You have to deploy it to a web server. Or try to load it with a script tag. Like this:

Your priorities.json file:
var jsonObject = {
"start": {
    "count": "5",
    "title": "start",
    "priorities": [
        {
            "txt": "Work"
        },
        {
            "txt": "Time Sense"
        },
        {
            "txt": "Dicipline"
        },
        {
            "txt": "Confidence"
        },
        {
            "txt": "CrossFunctional"
        }
    ]
}
}

Or declare a callback function on your page and wrap it like jsonp technique:

Your priorities.json file:
jsonCallback({
    "start": {
        "count": "5",
        "title": "start",
        "priorities": [
            {
                "txt": "Work"
            },
            {
                "txt": "Time Sense"
            },
            {
                "txt": "Dicipline"
            },
            {
                "txt": "Confidence"
            },
            {
                "txt": "CrossFunctional"
            }
        ]
    }
    })

Using script tag is a similar technique to JSONP, but with this approach it's not so flexible. I recommend deploying it on a web server.
With user interaction, javascript is allowed access to files. That's the case of File API. Using file api, javascript can access files selected by the user from <input type="file"/> or dropped from the desktop to the browser.

A: The d3.js visualization examples I've been replicating on my local machine.. which import .JSON data.. all work fine on Mozilla Firefox browser; and on Chrome I get the cross-origins restrictions error.
It's a weird thing how there's no issue with importing a local javascript file, but try loading a JSON and the browser gets nervous. There should at least be some setting to let the user over-ride it, the way pop-ups are blocked but I get to see an indication and a choice to unblock them.. no reason to be so Orwellian about the matter. Users shouldn't be treated as too naive to know what's best for them.
So I suggest using Firefox browser if you're working locally. And I hope people don't freak out over this and start bombing Mozilla to enforce cross-origin restrictions for local files.

A: As the jQuery API says: "Load JSON-encoded data from the server using a GET HTTP request."
http://api.jquery.com/jQuery.getJSON/
So you cannot load a local file with that function. But as you browse the web then you will see that loading a file from filesystem is really difficult in javascript as the following thread says:
Local file access with javascript

A: I would try to save my object as .txt file and then fetch it like this:
 $.get('yourJsonFileAsString.txt', function(data) {
   console.log( $.parseJSON( data ) );
 });

A: I have Used Following Methods But non of them worked:
   // 2 Method Failed

        $.get(
            'http://www.corsproxy.com/' +
            'en.github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
            function (response) {
                console.log("> ", response);
                $("#viewer").html(response);
            });
// 3 Method Failed

    var jqxhr = $.getJSON( "./json/movies-coming-soon.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  console.log( "second complete" );
});

// 4 Method Failed

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   success: function(jsondata){
    console.log(jsondata)
   }
})

// 5 Method Failed

$.ajax({
   url: 'https://github.com/FEND16/movie-json-data/blob/master/json/movies-coming-soon.json',
   headers: {  'Access-Control-Allow-Origin': 'htt://site allowed to access' },
   dataType: 'jsonp',
   /* etc */
   success: function(jsondata){

   }
})

What worked For me to simply download chrome extension called "200 OK!" or Web server for chrome and write my code like this:
// Worked After local Web Server

        $(document).ready(function () {
            $.getJSON('./json/movies-coming-soon.json', function (data) {
              var movie_name = '';
              var movie_year = '';
                $.each(data,function(i,item){
                    console.log(item.title,item.year,item.poster)
                    movie_name += item.title + "  " + item.year + "

"

                    $('#movie_name').html(movie_name)

                })

            })

        })

Its because you can not access local file without running local web server as per CORS policy so in order to running it you must have some host server.


text:
Q: React, Mocking API For this project I must not use a react library. I would like to be able to acces the data via a local JSON file (db.json for example) if I don't have access to the API (but retrieve the data from the API if I have access to it). How can I do this?
I make a useFecth :
import { useState, useEffect } from 'react'

export function useFetch(url) {
    const [data, setData] = useState({})
    const [isLoading, setLoading] = useState(true)
    const [error, setError] = useState(false)

    useEffect(() => {
      if (!url) return
      setLoading(true)
      async function fetchData() {
        try {
          const response = await fetch(url)
          const data = await response.json()
          setData(data)
        } catch (err) {
          console.log(err)
          setError(true)
        } finally {
          setLoading(false)
        }
      }
      fetchData()
    }, [url])
    return { isLoading, data, error }
  }

and I display datas in different pages :
import { useFetch } from "../../utils/hooks";
import logements from "../../__mock__/db.json"

function Logement() {
  const { logementId } = useParams();

  const {
    data: logement,
    isLoading,
    error,
  } = useFetch(`http://localhost:8000/api/logements/${logementId}`);

  if (isLoading) return
LOADING...
;

  if (error) {
    return <Error />;
  }

  return (

      <Slider slides={logement.pictures} />

{logement.title}

{logement.location}

            {logement.tags.map((tag, index) => (
              <Tags key={index} getTag={tag} />
            ))}

          <Rating rating={logement.rating} />
          <Host host={logement.host} />

        <Accordion title="Description" content={logement.description} />
        <Accordion title="Equipement" content={logement.equipments} />

  );
}

export default Logement;

import { useFetch } from "../../utils/hooks";
import logements from "../../__mock__/db.json"

function Home() {
  const {
    data: logementList,
    isLoading,
    error,
  } = useFetch(`http://localhost:8000/api/logements`);

  if (isLoading) return
LOADING...
;

  if (error) {
    return <Error />;
  }

  console.log(logementList);

  return (
    <Wrapper>
      <Banner image={image} title={Slogan} className="banner" />
      <HomeWrap>
        <Logements>
          {logementList.map((logement) => {
            console.log(logement._id);
            return (
              <CardWrapper key={logement.id}>
                <Link to={`/logement/${logement._id}`}>
                  <Card cover={logement.cover} title={logement.title} />
                </Link>
              </CardWrapper>
            );
          })}
        </Logements>
      </HomeWrap>
    </Wrapper>
  );
}

export default Home;

Thanks for your answer.

A: You can either create node server and add your all json there or use
google firebase to handle response if api is not available through url.
In promise then check if correct status is available in api otherwise call node server.


text:
Q: About the cases in the proof for Stallings automaton completness for a f.g. subgroup H of a free group F Context
Consider the following Theorem from a lecture about algorithmic group theory, I'm taking at the moment:

Let $N \not =\{1\}$ be a finite generated normal subgroup of a free group $F_A$ with $A$ being the alphabet, and let $H\leq F_A$ be a finitely generated subgroup of $F_A$ with $N\leq H$. Then the Stallings automaton $\Gamma(H)$ for the subgroup $H$ is complete.

I'm trying to understand the following proof:

We proof, that for any $a \in A \cup \overline{A}$ we can find a reduced word $v_a = av \in N$:
Let $w$ be a generator of $N$, then write $w$ as reduced word and $w = uv\overline{u}$ with $v$ being cyclic reduced. Now add $v$ to the set of generators and consider and $a \in A \cup \overline{A}$.

*

*If $a$ apperars in $v$, then $v_a=v'av''$. The word $av''v' \in N$ is reduced

*If $\overline{a}$ appears in $v$, then add $\overline{v}$ to the generators and considere $\overline{v}_a$

*If neither $a$ nor $\overline{a}$ appear in $v$, then $v_a=av\overline{a} \in N$ is reduced

For every word $uw \in H$ also $uv_aw \in H$, because $N$ is a normal Subgroup in $H$:
$$uv_aw = uw\overline{w}v_aw \in H\cdot N \subset H$$
Now stick all words $v_a$ to every node as petal. This does not produce nodes of degree 1.
Now every petal can be stallingsreduced completly, which proves that $\Gamma(H)$ has been complete already.

My question
I get the basic principle of the proof, tyring to complete $\Gamma(H)$ just for showing that this is redundant. But what seems strange to me, is the way we seperate cases for $v_a$. The last case for generating $v_a$ seems to be the most straightforward to me and I understand that this case does not work if $v$ starts with $\overline{a}$ or ends with $a$ because it isn't reduced and we therefore need the other two cases. But why are we interested in $a, \overline{a}$ appering anywhere in $v$, I don't see a problem with the last case when $a$ or $\overline{a}$ is contained in any other place of $v$.
So,  is there a specific reason, why the first two cases are more general than needed?


text:
Q: filter functions multiple times I have the following representative spreadsheet:

I am wanting to list the documents by using Xs like so:

So far, I have been able to get "(A) Document 1" by using formula
=JOIN(" ",,FILTER(F3:G4,F5:G5="X"))
But that does not work if I put a x in "(B) Document 1" or if I put an x in multiple columns.
How can one accomplish listing documents using Xs using a formula?


text:
Q: Changing the value of an input from another input on keyup using jQuery I have two inputs set up to simultaneously convert lbs to kgs and kgs to lbs on keyup depending on which input you use. I also have an error function to run if the input is not a number. My conversion works well for both inputs on keyup and the error as well, initially, but if I clear the inputs or switch from one to another , I lose the error function and the clear function doesn't clear the input completely in the second one, it leaves a number, 0.00. I am using a jquery plugin, jquery number to round the numbers to two places.
Here is a jsFiddle and my code:
 $(document).ready(function () {
 var kg = 0.453
 $('#weight_lb').on('keyup', function () {
    var wtvalueL = parseFloat($('#weight_lb').val());
    if (!isNaN(wtvalueL)) {
        $("#weight_kg").val($("#weight_lb").val() * kg).number(true, 2);
    } else { // the input wasn't a number
        $('#weight_lb').val('');
        $(".wt_error").fadeIn();
        setTimeout(function () {
            $(".wt_error").fadeOut();
        }, 2000);
        return false;
    }
 });
 $('#weight_kg').on('keyup', function () {
    var wtvalueK = parseFloat($('#weight_kg').val());
    if (!isNaN(wtvalueK)) {
        $("#weight_lb").val($("#weight_kg").val() / kg).number(true, 2);
    } else { // the input wasn't a number
        $('#weight_kg').val('');
        $(".wt_error").fadeIn();
        setTimeout(function () {
            $(".wt_error").fadeOut();
        }, 2000);
        return false;
    }
});
$(".clear").on('click', function () {
    $("#weight_lb").val("").attr('placeholder', 'Enter Weight');
    $("#weight_kg").val("").attr('placeholder', 'Enter Weight');
});
});


text:
Q: How to Invoke API in WSO2_AM from WSO2_ESB Proxy Service I have published an API in WSO2AM and the url shown in store is https://{ip}:8243/phoneverify/1.0.0
Now what I'm trying to do is call this from ESB Proxy service (which will later be invoked by a scheduler) as follows,
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
       name="a"
       transports="https,http"
       statistics="disable"
       trace="disable"
       startOnLoad="true">
   <target>
      <inSequence>
         <log level="full"/>
         <send>
            <endpoint>
               <http method="get"
                     uri-template="https://{ip}:8243/phoneverify/1.0.0/CheckPhoneNumber">
                  <timeout>
                     <duration>30000</duration>
                     <responseAction>fault</responseAction>
                  </timeout>
               </http>
               <property name="Authorization"
                         value="Bearer aaa4663b5851e06f2f1bc6e871fd20b7"
                         scope="axis2"/>
            </endpoint>
         </send>
      </inSequence>
      <outSequence>
         <log level="full"/>
      </outSequence>
   </target>
   <description/>
</proxy>

But when I try this it gives org.apache.axis2.AxisFault: Read timed out and in the server
[2015-03-20 08:50:48,481]  INFO - LogMediator To: /services/a.aHttpSoap12Endpoint, WSAction: urn:mediate, SOAPAction: urn:mediate, MessageID: urn:uuid:ce224d0e-f158-458c-b0be-ffeb09198e47, Direction: request, Envelope: <?xml version="1.0" encoding="utf-8"?><soapenv:Envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope"><soapenv:Body></soapenv:Body></soapenv:Envelope>
[2015-03-20 08:50:48,500]  INFO - TimeoutHandler This engine will expire all callbacks after : 120 seconds, irrespective of the timeout action, after the specified or optional timeout

[2015-03-20 08:50:49,289] ERROR - TargetHandler I/O error: Host name verification failed for host : {ip}
javax.net.ssl.SSLException: Host name verification failed for host : 52.74.66.119
        at org.apache.synapse.transport.http.conn.ClientSSLSetupHandler.verify(ClientSSLSetupHandler.java:152)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.doHandshake(SSLIOSession.java:285)
        at org.apache.http.nio.reactor.ssl.SSLIOSession.isAppInputReady(SSLIOSession.java:380)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:118)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:160)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:342)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:320)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:280)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:106)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:604)
        at java.lang.Thread.run(Unknown Source)
[2015-03-20 08:50:49,320]  WARN - EndpointContext Endpoint : AnonymousEndpoint will be marked SUSPENDED as it failed
[2015-03-20 08:50:49,320]  WARN - EndpointContext Suspending endpoint : AnonymousEndpoint - current suspend duration is : 30000ms - Next retry after : Fri Mar 20 08:51:19 UTC 2015

I could invoke the API using Chrome Advanced Rest Client. Therefore what am I doing wrong in, invoking this through the proxy service?

A: If your API is expecting a REST/JSon message, in your Proxy (WSO2 ESB) you should add <property name="messageType" value="application/json" scope="axis2" type="STRING"/> before of <send>.
If your API is expecting REST/XML, then use application/xml.
Regards.

A: For the "Host name verification failed for host" exception, please try out the config suggested in wso2.org/jira/browse/APIMANAGER-2089
And also, in your proxy service, you have to use the header mediator for setting  Authorization header.
<header name="Authorization" value="xxxxxx" scope="transport"/>


text:
Q: sklearn and SVMs with polynomial kernel I am using sklearn for python to perform cross validation using SVMs. I tried with the linear and rbf kernels and it all works fine. When i run it with the polynomial kernel though it never finishes. It has been running for 8 hours and still nothing. The dimensionality of the input X is (1422, 2)
def SupportVectorMachines(X,y):
     clf = svm.SVC(C=1.0, kernel='poly', degree=3, gamma=2)
     classifier = clf.fit(X,y)
     score = cross_validation.cross_val_score(classifier, X,y, cv=10, n_jobs=1).mean()
     return score

Any ideas why is that?
Thanks

A: Try reducing C (try C= 0.001,0.01,0.1). C is the penalty parameter and as C gets bigger, the model tries to reduce the penalty, and so takes more time to train.
Or, try reducing the number of cross validation folds. Since the dataset consists of only 1422 points, try using cv=5. This will take a smaller running time.

A: Try setting (max_iter = 1e5).
Something like:
    clf = svm.SVC(C=1.0, kernel='poly', degree=3, gamma=2,max_iter = 1e5)

It gives the following error, but terminates:
    /usr/local/lib/python3.6/dist-packages/sklearn/svm/_base.py:231: ConvergenceWarning: Solver terminated early (max_iter=100000).  Consider pre-processing your data with StandardScaler or MinMaxScaler.  % self.max_iter, ConvergenceWarning)


text:
Q: Is there a node/npm equivalent for Ruby's `bundle open #{gem_name}`? bundle open #{gem_name} opens a gem you have installed in the application specified by BUNDLER_EDITOR or EDITOR if the former is not present.
Obviously it is possible to open the actual location instead, I'm just wondering if node/npm have a similar helper feature.

A: You can use the npm edit <pkg> command to do this

Description
Opens the package folder in the default editor (or whatever you've configured as the npm editor config -- see npm-config.)
After it has been edited, the package is rebuilt so as to pick up any changes in compiled packages.
For instance, you can do npm install connect to install connect into your package, and then npm edit connect to make a few changes to your locally installed copy.
Configuration
editor

*

*Default: EDITOR environment variable if set, or "vi" on Posix, or "notepad" on Windows.

*Type: path

The command to run for npm edit or npm config edit.


text:
Q: Navigating from div tags within the same page using buttons? I am developing a website using asp.net/C#
I want to create a button that can save user data then move to a div tag at the same page.
I already did the saving part, but how do I make the same button to navigate to a different div tag within the same page?
some people use the response.redirect method to navigate to a different page. I want to navigate to a div tag within the same page. For example:
Experience
after I press that it will take me to:

I want to do the same but with button that can do both that and saving to a DB. As I said, I already did the saving part.
I tried this:
<asp:Button ID="Button1" runat="server" Text="Save & Continue" OnClientClick="#experience" OnClick="Button1_Click" />
But it didn't work.
any ideas? I am trying to access that div tag from code behind

A: If this is WebForms and you don't want to use javascript, then, after you do the save, you can do a Response.Redirect to the same url, but with the anchor tag, e.g. Response.Redirect("myPage.aspx#experience").
This really depends on the rest of your code though. I suggest posting the relevant parts of your code behind so that we can better see what you have done. Also, don't try to avoid javascript - it is too useful to avoid.

A: ASP.NET has a Focus method that can be applied to the following ASP.NET server controls:

*

*Button

*LinkButton

*ImageButton

*CheckBox

*DropDownList

*FileUpload

*HyperLink

*ListBox

*RadioButton

*TextBox
At the end of your Button1_Click event handler code-behind, add something along this lines of this:
TextBoxExperience.Focus();

Note - The TextBox control with ID of TextBoxExperience control would be inside of the experience DIV.


text:
Q: Controlling VLC via c# I am writing an application that will open vlc, add a file to its playlist, and play it. I am having a few issues on the last 2.
 AXVLC.VLCPlugin alxplugin1 = new AXVLC.VLCPlugin();

                alxplugin1.addTarget("C:\\test.avi", null, AXVLC.VLCPlaylistMode.VLCPlayListInsert, 0);
                alxplugin1.play();

This isn't working... Any ideas?
Thanks

A: The newer version of VLC needs "file:///" in beginning of the file name. It should work if you add this. Please try the following and see if it solves your problem.
use:
 alxplugin1.addTarget("file:///" + "C:\\test.avi", null, AXVLC.VLCPlaylistMode.VLCPlayListReplaceAndGo,0);

A: C# can access VLC through it's COM layer. First thing to do is to register the axvlc.dll. Open a cmd window and type:
C:\Windows\System32\regsvr32.exe C:\Program Files (x86)\VideoLAN\VLC\axvlc.dll

You should receive a dialog confirming that your dll was registered successfully. Open VisualStudio and create a new WinForms project and add a reference to the COM VLC COM object. Go to the Form cs file
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
          public Form1()
          {
               InitializeComponent();

               AXVLC.VLCPlugin2Class p = new AXVLC.VLCPlugin2Class();
               p.addTarget("C:\\zk.m4a", null, VLCPlaylistMode.VLCPlayListInsert, 0);
               p.play();
           }
     }
 }

Note: The VLCPluginClass was deprecated, use VLCPlugin2Class


text:
Q: Deserialize into map[string]interface{} as a concrete map type type Foo struct {
    M map[string]interface{} `json:"m"`
}

type Bar struct {
    I int `json:"i"`
}

type Bar2 struct {
    S string `json:"s"`
}

func do() {
    concreteFoo1 := Foo {
        M: make(map[string]Bar),
    }
    json.Unmarshal([]byte(`{"m": {"a": { "i": 1 }}}`), &concreteFoo1)

    concreteFoo2 := Foo {
        M: make(map[string]Bar2),
    }

    json.Unmarshal([]byte(`{"m": {"a": { "s": "hello" }}}`), &concreteFoo2)

}

fails to compile with:

cannot use make(map[string]Bar) (type map[string]Bar) as type
map[string]interface {} in field value
cannot use make(map[string]Bar2) (type map[string]Bar2) as type
map[string]interface {} in field value

How can I get this to compile, and support both variants of Foo?

A: Change Foo.m to be map[string]Bar instead of what you have, that will allow it to compile. To make it work, you need to change Foo.m to Foo.M and Bar.i to Bar.I. The Go JSON library will not unmarshal to or marshal from unexported properties. Mapping the uppercase properties to lowercase JSON elements requires using tags. Full working example here.

A: Change this line:
M map[string]interface{} json:"m"
into :
M interface{} json:"m"
https://play.golang.org/p/qRxo81amA7

A: If the set of possible Bar types is infinite you should use the solution from Stud's answer. After unmarshaling you just need to do one type assertion to get the map, which is much better then doing type assertion on each value of a map[string]interface{} type.
If, however, the set is limited to only a few types you could create a parent Bar type that embeds the list of all the possible Bar variations. In case there's a possibility that the fields of the embedded types would collide you can still have the embedding type implement the json.Unmarshaler interface and do some custom logic on what to unmarshal where.
E.g. something like this:
type BarSet struct {
    *Bar
    *Bar2
}

type Bar struct {
    I int `json:"i"`
}

type Bar2 struct {
    S string `json:"s"`
}

https://play.golang.org/p/tJfqtnP-CX
And if you want to be as strict as possible you should create separate Foo types, each with their distincitve M map[string]... field.

A: You can make generalized interface
type Foo struct {
    M map[string]Ibar `json:"m"`
}

type Ibar interface{}

And unpack into it.
When you need specific value of variable make type assertion.
https://play.golang.org/p/fcs-Yp-ck2

A: I've looked again and think custom unmarshaler can be good option.
func (f *Foo) UnmarshalJSON(b []byte) error {
    var tmp struct {
        M map[string]json.RawMessage `json:"m"`
    }
    var foo = Foo{
        M: make(map[string]interface{}),
    }
    var err error
    //for key, rawValue := range
    err = json.Unmarshal(b, &tmp)
    if err != nil {
        return err
    }
    for key, rawValue := range tmp.M {
        var bar Bar
        if json.Unmarshal(rawValue, &bar) == nil && bar.I != 0 { // custom check
            foo.M[key] = bar
            continue
        }
        var bar2 Bar2
        if json.Unmarshal(rawValue, &bar2) == nil && bar2.S != "" { // custom check
            foo.M[key] = bar2
            continue
        }
    }
    *f = foo
    return nil
}

Advantages:

*

*Logics in one place

*Standard call UnmarshalJSON

*Can handle several subobjects
https://play.golang.org/p/ug9rewqjWw


text:
Q: 2d projectile trajectory? My object has a point x,y this always changes as the mouse drags it around inside a 800x600 box. My object also rotates to an angle set by the mouse it can be any 360 degree. My issue is now how to shoot a projectile from that angle and of course from that XY position. The projectile only needs to go in a straight line but It need to be moving in the correct angle as the Main object was. I have the angle and I have the XY position all I need is the formula to make it move across the grid from the appropriate angle.
EDIT -
Current JSFIDDLE with projectile not shooting at the correct angle.
http://jsfiddle.net/vbk4Z/16/

A: The standard formulae are:
xn = x0 + v * t * cos(theta)
yn = y0 + v * t * sin(theta)

Where (x0, y0) are the original position, v is the velocity required, theta is the angle (in radians) and t is the time since the projectile was fired.
Note that this uses the classic cartisian convention of angles being measured anticlockwise relative to the positive x axis, and with the y axis facing up.
If you're using browser coordinates, and happen to have chosen to use bearings (clockwise relative to "up" / "north") then you need to swap some signs and trig functions:
xn = x0 + v * t * sin(theta)
yn = y0 - v * t * cos(theta)


text:
Q: Unable to Parse ampersand in PHP string I am trying to parse the ampersand value in a PHP string. It keeps returning blank values after I run my code and I am sure it is because of the 'ampersand' value in my variable ($area). I tried htmlspecialchars, html_entity_decode but to no avail. Please see code below:
<?php

/** Create HTTP POST */
$accomm = 'ACCOMM';
$state = '';
$city = 'Ballan';
$area = 'Daylesford & Macedon Ranges';
$page = '10';

$seek = '<parameters>

<row><param>SUBURB_OR_CITY</param><value>'. $city .'</value></row>
<row><param>AREA</param><value>'. $area .'</value></row>

</parameters>';

$postdata = http_build_query(
array(
 'DistributorKey' => '******',
 'CommandName' => 'QueryProducts',
 'CommandParameters' => $seek)
);

$opts = array(
'http' => array(
'method'  => 'POST',
'header'  => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata)
);

/** Get string output of XML (In URL instance) */

$context  = stream_context_create($opts);
$result =   file_get_contents('http://national.atdw.com.au/soap/AustralianTourismWebService.asmx/CommandHandler?', false, $context);

?>

Pls how do I fix this
Thanks

A: XML is not HTML, and vice-versa. You cannot have a bare & in an XML document since it is a special character in XML documents. If you're just defining a static string like this your can replace it with & and move on with your day.
If you need to encode arbitrary strings that may or may not contain & or another XML special char, then you'll need functions like:
function xmlentity_encode($input) {
    $match = array('/&/', '/</', '/>/', '/\'/', '/"/');
    $replace = array('&', '>', '<', ''', '"');
    return preg_replace($match, $replace, $input);
}

function xmlentity_decode($input) {
    $match = array('/&/', '/>/', '/</', '/'/', '/"/');
    $replace = array('&', '<', '>', '\'', '"');
    return preg_replace($match, $replace, $input);
}

echo xmlentity_encode("This is testing & 'stuff\" n <junk>.") . "\n";
echo xmlentity_decode("This is testing & 'stuff" n >junk<.");

Output:
This is testing & 'stuff" n >junk<.
This is testing & 'stuff" n <junk>.

I'm fairly sure that PHP's XML libs do this for you transparently, [and also respecting the character set] but if you're manually constructing your own XML document then you have to ensure that you're aware of things like this.


text:
Q: Xamarin.Forms TabbedPage - iOS with 'More..' tabitem Good morning
I have created a TabbedPage where untill now I had 4 tabs. Everything was working as expected however I have to add two more tabs and the problem begins.
On Android platform result is as expected. I do contain two more TabBarIcon on my TabBar. However on iOS instaed of having two TabBarIcons, I have one additional whch is called "More" and there by design of iOS I have DropDown to pick which I wanna select.
I wonder if there is any option to avoid the 'More' button and keep having six tabs.
I was looking around the interent but couldn't find any custom renderer for iOS.
Is is possible ?

A: This behavior is  designed by Apple , check the following official docs

The tab bar has limited space for displaying your custom items. If you add six or more custom view controllers to a tab bar controller, the tab bar controller displays only the first four items plus the standard More item on the tab bar.

Actually too many tabs reduce the tappable area of each tab and might increase the complexity of your interface.
If you want , you can write your own tabbed page that allows 6 or more tabs, but I suggest you not do that, because Apple will reject your app because it doesn't meet apples design-rules.


text:
Q: How to use and save Emoji's on Laravel using Mysql I have a web app I built using Laravel 5.2 , my question is how do I store then show emoji's. At the moment when I use an emoji from my iPhone , fire for instance, after saving the database returns ???? . Ive set the
'charset' = 'utf8mb4';
'collation' = 'utf8mb4_unicode_ci'
but still get the same result. Do i need to install a package or something?

A: Make sure you have the charset and collation correctly setup in the database config file as well, to ensure Laravel actually knows what charset to use when saving:
// config/database.php

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_general_ci',
    'prefix' => '',
    'strict' => false,
    'engine' => null,
],


text:
Q: How to add array values after exceeding a certain length in java I am trying to work out the best way to add array values when they exceed a certain length. The program will allow a user to input values into the array. Once the user enters the amount of numbers (can be as much as they want). The numbers should not exceed 6 columns, and if they do they should be added from right to left of the array. See below
The 12 numbers inputted by the user:
arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6};

A new array should be made which will look like this:
newArrNumbers = int [2, 4, 6, 8, 10, 12]

Resulting in only 6 slots.
I have no idea on how to code this. I only know that this could be possible with an if statement like below. I am a beginner and would like to know a solution from someone experienced.
if (arrNumbers.length > 6)

A: You can easily iterate through the rest of Array.
int sum=0;
for(int i=6;i<arrNumbers.length;i++){
sum+=arrNumbers[i];
}
arrNumbers[5]=sum;

A: I think what you are looking for is this
int[] arrNumbers = new int[] {1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6};
int[] res = new int[6];

// iterate over the initial array and chunk it. 6 will be our chunk per requirements.
for (int i = 0; i < arrNumbers.length; i += 6) {
    // create a sub array for the first 6 numbers.
    int[] ints = Arrays.copyOfRange(arrNumbers, i, Math.min(arrNumbers.length, i + 6));
    // add the first chunk to our resulting array. Repeat until needed.
    for (int j = 0; j < ints.length; j++) {
        res[j] += ints[j];
    }
}

Result: res: {2, 4, 6, 8, 10, 12}
This will work for any array size for the arrNumbers variable.

A: A more concise and efficient answer:
    int[] arrNumbers = new int[] { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6};
    int[] newArrNumbers = new int[6];

    for(int i  = 0; i < arrNumbers.length ; i++){
        newArrNumbers[i % 6] += arrNumbers[i];
    }

output: [2, 4, 6, 8, 10, 12]


text:
Q: Asp.Net Core Razor Pages Ajax Post is Null using FromBody I'm developing an Asp.Net (6.0) Razor Pages application. One of the pages needs to Post data using AJAX, however, the Post is always Null.
I have tried to use the previous related questions to this on Stackoverflow, but my problem still persists.
This is my Razor Page (cshtml)
@Html.AntiForgeryToken()

<script type="text/javascript">
$(function () {

$('button').on('click', function(){

const token = $('[name="__RequestVerificationToken"]').val();
var data = { "MyVar": "Simon", "MyNum": 21 };

$.ajax({
    url: '?handler=SaveOrder',
    method: "post",
    contentType: "application/json",
    dataType: 'application/json; charset=utf-8',
    headers: {
        "RequestVerificationToken" : token
    },
    data: JSON.stringify(data)
});
</script>

This is my PageModel for the same Razor Page

As you can see, the Ajax Post is working in that it hits the appropriate handler method, but no data is posted.
Can anyone help, please?
Thanks.