text:
Q: Selenium, default values assigned to web elements instead of the ones i am search for I am sending text to an input field then within the array of elements searching for specific by checking if element text  equal street address
As you can see i have Thread sleep which is not the right approach, the reason i am using this is because i am not to sure how to proceed with the current state of the default values.
When i click on input field there are some values by default within the web elements i am locating which means if i remove Thread sleep it will fail due to the fact that the default values will be assigned to the web elements so i am wondering what can i do in such case
Since i know the default values i could potential just find one and wait until it disappears but thinking if there is a better approach to deal with it
default values on input click
the text i am then entering
public LocatedCarParksMap searchForCarPark(String carPark,String location) {
        clickOnSearchInput();
        searchCarPark.sendKeys(carPark);

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (WebElement i : locatedCarParkAddresses) {
           if(i.getText().equals(location)){
               click(i);
           }
        }

        return new LocatedCarParksMap(driver);
    }

A: You can look for some loaders that are appearing in between you enter the search text and the search result appearance. You can wait for that loader to vanish. After that, you can look for your search results.
Even if you have/don't have loader, this similar FluentWait approach should work:
public LocatedCarParksMap searchForCarPark(String carPark,String location) {
    clickOnSearchInput();
    searchCarPark.sendKeys(carPark);

    //If loader available, write code here to wait for your loader to vanish. Just a simple invisibilityOf should work.

    boolean clickStatus = waitAndClickSearchElement(location);

    if(! clickStatus) {
        throw new Exception(carPark + " is not available in Search Results");
    }

    return new LocatedCarParksMap(driver);
}

public boolean waitAndClickSearchElement() {
try {
    //Change this timeout of 10 sec according to your need.
    WebDriverWait webDriverWait = new WebDriverWait(driver,10);
    //Increased the polling time to 2 secs to avoid checking the results frequently.
    webDriverWait.pollingEvery(Duration.ofSeconds(2))
    //Ignoring these 2 exceptions as they are more likely to occur.
    webDriverWait.ignoring(NoSuchElementException.class, StaleElementReferenceException.class);
    //This until method keeps checking the text for 10 secs. Once it finds the element, will click on it.
    return webDriverWait.until(driver -> {
       for (WebElement weAddress : locatedCarParkAddresses) {
           if(weAddress.getText().equals(location)){
               weAddress.click();
               return true;
           }
       }
       return false;
       });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

There is one edge case here. Lets say your expected search result is already part of default search results, the above code may throw StaleElementReferenceException. But we have handled it so I hope it would work fine. Please let me know if you have any issues.


text:
Q: Hat position is wrong in iOS app, scrolls with page When visiting my profile on the mobile app, my hat scrolls with the page:

It doesn't stay linked to my icon at the top.
I'm on an iPhone 6+ running iOS 9.2 and version 1.4.1 of the SE app.

A: Update Actually it shipped the next day!

This will be fixed either next week or in December 2016.
I am so sad about this.  Like, really, really sad.
WinterBash hats are on a separate overlay view which updates its content offset on scroll as follows:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.winterBashOverlayView.contentOffset = scrollView.contentOffset;
}

Unfortunately, I inserted this method inside a #ifdef DEBUG block so it worked perfectly during development but is completely excluded from the release.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trigger event in jquery without a namespace With the current version of jQuery (1.8.3) you can still use the following code (showing both a click with and without a namespace):
$("span")
    .on("click", function(e) { console.log('click without a namespace'); })
    .on("click.namespace", function(e) { console.log('click with a namespace'); })
    .trigger("click!"); // "click without a namespace"

JSFiddle
However, that seems to be removed in 1.9. Is there a way in the new version of jQuery (the test version) to replicate this feature? Or do I have to create a custom event like this:
$("span")
    .on("click", function(e) { $(this).trigger("customevent"); })
    .on("click.namespace", function(e) { console.log('click with a namespace'); })
    .on("customevent", function(e) { console.log('"click" without a namespace'); })
    .trigger("customevent");

JSFiddle

A: You can call that using
.trigger("click.$")
as we found it is because regex
http://jsfiddle.net/oceog/RczDZ/10/


text:
Q: "UnicodeError: UTF-16 stream does not start with BOM" when opening file that apparently has a BOM I have a project in which most of the files are UTF-16 but one is UTF-8. Having put the correct encoding ("utf_8" or "utf_16") into strOpenEncoding, I tried this:
for strInput in open(strInputFileName, "r", newline="\n", encoding=strOpenEncoding):

I get this response:
UnicodeError: UTF-16 stream does not start with BOM

I have opened the file it is trying to open manually, and it definitely contains a byte-order mark and is definitely UTF-16. What am I doing wrong?


text:
Q: How to check whether a u64 number larger than 2 ^ 54 is divisible by f64 with the minimal precision loss? For a u64 number less than 2 ^ 54 it can be done without much of precision loss by casting to f64:
((6 as f64) % 1.5) < f64::EPSILON

For larger numbers, there will be a significant precision loss:
1u64 << 63           // 9223372036854775808
(1u64 << 63) as f64  // 9223372036854776000

and divisibility will be checked for a different number.
Context: JSONSchema's multipleOf keyword implementation
Question: What is the most efficient way to check divisibility for u64 / i64 numbers that do not fit the f64 mantissa size (f64::MANTISSA_DIGITS which is 53)?

A: Here is a solution given that u is some integer and x is a finite non-zero IEEE-754 binary64 number with which we do IEEE-754 arithmetic. x is presumed to represent one specific number, as specified by IEEE-754, and prior rounding errors occurring while obtaining x are not considered. This answer speaks to the mathematics involved, not to the Rust semantics, as I am unfamiliar with Rust.
First, find the representation of x = F • 2E, where F is an odd integer and E is an integer. A simple method for this is:

*

*Set F to x and E to 0.

*While F is not an integer, multiply F by two and subtract one from E.

*While F is even, divide F by two and add one to E.

All of the above operations can be performed in IEEE-754 arithmetic with no rounding errors. If Rust offers a method to separate the significand and exponent of a floating-point number, akin to C's frexp function, then incorporating it into the above can improve efficiency.
Now consider whether u is a multiple of x = F • 2E. By definition, it is if and only if there is an integer k such that u = k • F • 2E. We will see this is so if and only if u is a multiple of F and is a multiple of 2E, and each of these can be tested.
If 2E is an integer (E is non-negative) and such a k exists, then u is a multiple of F and is a multiple of 2E. Conversely, if u is not a multiple of F or is not a multiple of 2E, then no such k exists (by way of the fundamental theorem of arithmetic).
F is necessarily within bounds of the requested integer format (it is at most 53 bits), and we assume F can be converted to that format. Then divisibility of u by F can be tested. If 2E exceeds the maximum value of the integer format in which u is represented, then u is not a multiple of 2E. Otherwise, 2E can be converted to the format, and the divisibility of u by 2E can be tested.
If 2E is not an integer (E is negative), then, if the required k exists (so u is a multiple of F), it is a multiple of 2−E. Conversely, if k is not a multiple of 2−E, then k • F • 2E is not an integer, so it cannot equal u. Thus u is a multiple of x if and only if u is a multiple of F.


text:
Q: Combine two tables into one table without using join and without the result creating cartesian product How do I make a table of results of two different ratings without creating a cartesian product. diffrating and hostrating are two different types of user ratings. The users are rating the spots which are are labeled with spotId. userdiffrating and userhostrating are linking the users ratings to the correct spots. I am trying to get all the ratings for a specific spot in a table. Sample data and the expected output are bellow.
Table contents:
userdiffrating:
-------------------------------
| RatingId | userId  | spotId |
-------------------------------
| 1        | 1       | 1      |
-------------------------------
| 2        | 2       | 1      |
-------------------------------
| 3        | 1       | 2      |
-------------------------------

diffrating:
----------------------
| RatingId | userId  |
----------------------
| 1        | 5       |
----------------------
| 2        | 2       |
----------------------
| 3        | 4       |
----------------------

userhostrating:
-------------------------------
| RatingId | userId  | spotId |
-------------------------------
| 1        | 1       | 1      |
-------------------------------
| 2        | 2       | 1      |
-------------------------------
| 3        | 1       | 1      |
-------------------------------

hostrating:
----------------------
| RatingId | userId  |
----------------------
| 1        | 1       |
----------------------
| 2        | 3       |
----------------------
| 3        | 4       |
----------------------

This is what I originally tried but this creates a cartesian product:
SELECT D.rating diffrating, H.rating hostrating FROM diffrating D
JOIN userdiffrating UD ON D.ratingId = UD.ratingId
JOIN userhostrating UH ON UD.spotId = UH.spotId
JOIN hostrating H ON UH.ratingId = H.ratingId WHERE UD.spotId = 1

Result from first query (cartesian product):
-------------------------
| diffrating| hostrating|
-------------------------
| 5         | 1         |
-------------------------
| 5         | 3         |
-------------------------
| 5         | 4         |
-------------------------
| 2         | 1         |
-------------------------
| 2         | 3         |
-------------------------
| 2         | 4         |
-------------------------

I tried this next query but I cant use a select statement that has more than one row as a subquery:
SELECT  D.rating AS diffrating, H.rating AS hostrating

FROM  diffrating D, hostrating H

WHERE D.ratingId = (SELECT ratingId FROM userdiffrating UD WHERE UD.spotId = 1)

AND H.ratingId = (SELECT ratingId FROM userhostrating UH WHERE UH.spotId = 1)

This is the expected result (all diff and host ratings for spotId = 1):
-------------------------
| diffrating| hostrating|
-------------------------
| 5         | 1         |
-------------------------
| 2         | 3         |
-------------------------
| NULL      | 4         |
-------------------------

This is the database:

Is this possible and how would this be done?
Thanks

A: I think what you are trying to code is this
SELECT dr.rating diffratingval, hr.rating hostratingval
FROM diffrating dr
JOIN userdiffrating udr
    ON dr.ratingid = udr.ratingid
JOIN userhostrating uhr
    ON udr.spotid = uhr.spotid
JOIN hostrating hr
    ON uhr.ratingid = hr.ratingid
        AND dr.ratingid = hr.ratingid
WHERE udr.spotid = 60;


text:
Q: Firstname or lastname case change query without unintended consequences. I am running the query below in Sybase application which works great but the consequences are when the first name is written like this, "ADNAN RAZA" it makes it "Adnan raza". Any function which I can use here to detect the position of letter after space or - and update. Can't do it manually there are more than 100k records.
update master set firstname =
upper(left(firstname,1))+lower(substr(firstname,2));

A: in Oracle SQL there is a function called initcap (character-expression).
Initcap returns character- expression with each word's first character in uppercase and the rest in lowercase.
i saw somewhere that in Sybase you have dbo.intcap(name) for this.

A: There is no solution for this at db level as it stands now.


text:
Q: The border goes all the way to the right So I made a a calculator to change kilogram to pound and I was going to add a border to a pelement but the bordergoes all the way to the right
So here is the html
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>HTML</title>

  <link rel="stylesheet" href="style.css">

  <input type="number" placeholder="Type Weight In Kilograms" id="kilograms">

0

0

And here is the css
*{
  padding: 0%;
  margin: 0%;
  box-sizing: inherit;
}

body {
    font-size: 15pt;
    width: 480px;
    height: 500px;
    box-sizing: border-box;
}
#kilograms {
  position: relative;
  top: 70px;
  left: 140px;
  border: 20px solid crimson;
  border-radius: 4px;
}
#pounds {
  position: relative;
  top: 100px;
  left: 240px;
}
.dinnars {
  border: 15px solid darkorchid;
  position: relative;
  top: 150px;
  left: 240px;
  border-radius: 4px;
}

A: Add width: min-content; to your .dinnars class. I would also delete the top and bottom attributes. They are unnecessarily restricting your sizing.
Also, get rid of the top left attributes.

*{
  padding: 0;
  margin: 0;
  box-sizing: inherit;
  box-sizing: border-box;
}

body {
    font-size: 15pt;
    // width: 480px;
    // height: 500px;
}

#kilograms {
  position: relative;
  // top: 70px;
  // left: 140p;
  border: 20px solid crimson;
  border-radius: 4px;
}
#pounds {
  position: relative;
  // top: 100px;
  // left: 240px;
}
.dinnars {
  border: 15px solid darkorchid;
  width: min-content;
  position: relative;
  // top: 150px;
  // left: 240px;
  border-radius: 4px;
}

.box{
  border:2px dotted green;
  width: 500px;
  height 500px;
}

  <input type="number" placeholder="Type Weight In Kilograms" id="kilograms">

0

0

A: The p-element is in relative position with the element that has a class .dinners at right, so applying border on the p-element will make the right hand border look bigger because of the of relative element that already has it's own border that look like it's merging with the one at the Left because of there is no space between the two. Also note that the box-sizing property affects the way properties are applied on elements. Maybe try using box-sizing: border-box.


text:
Q: Create URL for CActiveForm from within a widget inside a module I am writing a module for my site that will manage the Users. So in order to simplify my code, I wrote a "LoginWidget" view and made it accessible thru an actual derived class from  CWidget. Now I want to create an URL to the module. For now, I wrote it with the module ID typed in: $this->controller->createUrl("/user/user/login");. But how can I make it more "dynamic"? Let's say I changed the folder name from user to users. What code do I need to use to create an URL, that is relative to the module in which the widget is saved to?
I am using the latest Yii 1.1.x release.


text:
Q: Schwarz Reflection Across Circular Arc this is a basic question but I want to make sure I am understanding well (which I'm not haha).
Suppose we have an analytic function $f(z)$ on the disc of radius 2, centered at the origin.  Also, suppose there is an arc on the unit circle on which $f(z)$ is real.  Then we want to prove that $f(z)$ is constant.
Using the Cayley Transform, I know that reflecting across the real line with $z \mapsto \bar{z}$ is equivalent to $z \mapsto \frac{1}{\bar{z}}$ on the unit circle. If we call the subarc $\sigma \subset \partial \mathbb{D}$, then on $\sigma$ we have $$f(z) = \overline{f(\frac{1}{\bar{z}})}$$ in a neighborhood of $\sigma$.  Call the right half of the above equality $g(z)$.  Then $g(z)$ is analytic where defined, i.e. on the complement of $\overline{B(\frac{1}{2}, 0)}$ so by uniqueness, is equal to $f(z)$ on an annulus around $\partial \mathbb{D}$.
Here's where I'm not sure what to do.  I guess the idea is that since $f$ can be analytically extended from this annulus inward, so can $g$.  Geometrically it's obvious that this causes problems (ultimately it should have to either "flip" 0 to $\infty$ or fail the maximum modulus principle), but I can't put the proof together.  Can anyone help with the last details?
Thanks a lot!

A: Let $M = \text{max}_\overline{\mathbb{D}}(|f(z)|)$.  Using the notation of the question, note that on the complement of $\mathbb{D}$, $|g(z)|$ is bounded by $M$. Since $f$ and $g$ agree on an overlap (an annulus about the unit circle) they glue to an analytic $h$, which is entire since the union of the domains of $f$ and $g$ are all of $\mathbb{C}$.  But it's bounded by $M$ and thus constant, by Liouville's Theorem.


text:
Q: get mac address of the client machine from python Hi I am trying to capture the mac address of the client machine from python or java.I tried from java but no luck.its printing only for server mac address.I need client mac address.I tried some methods in python.
from uuid import getnode as get_mac
mac = get_mac()

The above code print uuid number of the machine.But I think it works only for server machine.I need to capture for client machine.Any help will be appreciated.

A: After a pip install netifaces:
import netifaces
print(netifaces.ifaddresses('wlan0')[netifaces.AF_LINK]['addr'])

Should print the mac address of your interface:
    ac:bc:32:ba:bd:cb
More info here

A: You can use system interfaces address file
def getmacaddress(interface):
    macaddress = open('/sys/class/net/'+interface+'/address').readline()
    return macaddress[0:17]

call this using MACADDRESS = getmacaddress("wlan0")
This will return your system macaddress.


text:
Q: Why JQGrid shows empty records in MVC 5? I have a problem that JQGrid load the data but show empty records. This is my controller action method:
public ActionResult Database(string server,string database, string username, string password)
        {
            UserAthentication U = new UserAthentication();
            U.ServerName = server;
            U.DatabaseName = database;
            U.Username = username;
            U.Password = password;
            Database db = new Database();

            var Names = db.GetDatabaseNames(U); //This method returns the string list and i debugged it it returns the data correctly.

            var jsondata = new
            {
                total = 1,
                page = 1,
                records = 0,
                rows = Names
            };

            return Json(jsondata, JsonRequestBehavior.AllowGet);
        }

This is JQgrid code:
$(document).ready(function () {
    $('#b1').click(function () {
        var server = $("#ServerName").val();
        var database = $("#DatabaseName").val();
        var username = $("#Username").val();
        var password = $("#Password").val();
        var URL = '/Home/Database?server=' + server+"&database="+database+"&username="+username+"&password="+password;

        $("#Grid").jqGrid({
            url: URL,
            datatype: 'json',

            colNames: ['Tables Name'],
            colModel: [

                {  name: 'TABLE_NAME', index: 'TABLE_NAME' },

            ],
            jsonReader: {
                root: 'rows',
                page: 'page',
                total: 'total',
                records: 'records',

                repeatitems: false
            },
            pager: $('#pager'),
            rowNum: 10,
            rowList: [10, 20, 30],
            width: 600,
            viewrecords: true,
            emptyrecords: 'No records to display',
            sortorder: "desc",
            caption: 'Databases',
            loadonce: false,

        });
    });

});

It shows the empty rows. There are 4 rows that should show and it shows 4 empty rows

A: colModel: [
    {  name: 'TABLE_NAME', index: 'TABLE_NAME' },
],

you do not use TABLE_NAME but instead you use columns name like this:
colModel: [
    {  name: 'Column_NAME', index: 'Column_NAME' },
    {  name: 'Column_NAME', index: 'Column_NAME' },
    {  name: 'Column_NAME', index: 'Column_NAME' },
    {  name: 'Column_NAME', index: 'Column_NAME' },
],


text:
Q: EACCES error after updating firebase-admin I just updated firebase admin and when I try to acces my firebase functions code, after I run firebase serve, I get EACCES error. I mention that before the update, the code was working fine.
I tried reinstalling the node modules, reinstalling firebase and firebase admin, running the serve command as admin, and also adding
  "engines": {
    "node": "8.15.0"
  },
to my package.json file
the full error:
i  functions: Beginning execution of "api"
!  Default "firebase-admin" instance created!
>  events.js:183
>        throw er; // Unhandled 'error' event
>        ^
>
>  Error: listen EACCES C:\Users\Berce\AppData\Local\Temp\firebase_emulator_invocation_2608.sock
>      at Server.setupListenHandle [as _listen2] (net.js:1343:19)
>      at listenInCluster (net.js:1401:12)
>      at Server.listen (net.js:1496:5)
>      at Function.listen (C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\node_modules\express\lib\application.js:618:24)
>      at Promise (C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:359:46)
>      at new Promise (<anonymous>)
>      at C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:332:15
>      at Generator.next (<anonymous>)
>      at C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71
>      at new Promise (<anonymous>)
>      at __awaiter (C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12)
>      at ProcessHTTPS (C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:329:12)
>      at C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:523:23
>      at Generator.next (<anonymous>)
>      at fulfilled (C:\Program Files (x86)\Nodist\bin\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:4:58)
>      at <anonymous>
>      at process._tickCallback (internal/process/next_tick.js:189:7)
>      at Function.Module.runMain (module.js:696:11)
>      at startup (bootstrap_node.js:204:16)
>      at bootstrap_node.js:625:3

A: Thanks to the comments I found out that the problem was known by firebase team. Is reproduced on windows, and there is no known way to fix it. So for now I had to fall back.
Thank you!


text:
Q: Conflict between on click events Hello guys I'm having a bad time trying to solve a conflict between two onclick events. My project has a canvas and a properties box.
I can add elements(pressing a button) to canvas by appending them to It (These elements have the class '.element' and they are divs, and the canvas is also a div element).
So, once I have an element on canvas, I can see It's properties (on the properties box) by clicking on It. To handle this click event I implemented the following function:
var canvas = $('#canvas');

 $(function(){
    canvas.delegate('.element','click', function(){
    // Here I update the properties box with information of the clicked element
    // and and some css to the element so user can know that It's selected
    });
 });

Now I want to implement a function that when I click elsewhere on the canvas, It clears the property box (once no element is selected). I tried doing this:
$(function(){
  canvas.on('click',function(){
         //Clear properties box here
  });
});

But now It cancels the first function (It's like only the second one is executed). Do you guys know how can I turn this situation around?

A: Add the event as an argument to the binding of the first function, and try adding #stopPropagation
canvas.on('click', '.element', function(e){
  // all your code here
  e.stopPropagation();
});

what's happening here is that by click the .element div, you trigger the first function, but because the .element is contained within the canvas, you're also triggering the second binding (which clears the box). stopPropagation prevents the event from bubbling up to any parent divs which will prevent you from triggering the second binding.
also, I'd recommend changing the way you're delegating (to how I've written it) because the #delegate method is deprecated.


text:
Q: Returning data with heavy use of predicates I am using .Net Core 2 web API with an architecture that uses predicates heavily which is causing some issues when I try to unit test my code with Moq.
Each of my repositories inherit from a base repository that has basic methods like this:
public T GetSingle(Expression<Func<T, bool>> predicate)
{
    return _context.Set<T>().FirstOrDefault(predicate);
}

public virtual IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)
{
    return _context.Set<T>().Where(predicate);
}

In my User controller Signup method I want to make sure that I don't allow duplicate emails and I do so like this:
var emailCheck = _userRepository.GetSingle(x => x.Email == user.Email);
if (emailCheck != null)
{
    // duplicate
    return StatusCode(StatusCodes.Status409Conflict, "This email is already in use.");
}

In my unit test I want to have a test to make sure that we don't allow duplicates so I set this up:
public void Signup_Fail_DuplicateEmail_Controller_Test()
{
    var user = UserHelper.CreateSignupUser();
    user.Email = "duplicate@test.com";
    var uRepo = new Mock<IUserRepository>();

    uRepo.Setup(u => u.GetSingle(x => x.Email == user.Email)).Returns(user);

    var uc = new UserController(uRepo.Object);
    var result = uc.Signup(user);

    var status = Assert.IsType<StatusCodeResult>(result);
    Assert.Equal(StatusCodes.Status409Conflict, status.StatusCode);
}

The Setup method always returns null no matter what I do. Now I have read in several places that Moq does not work with FirstOrDefault and other helper methods like it, but I am not sure what to do since my architecture is so reliant on predicates. Certainly want to avoid reworking my base repository, but I need to be able to run tests like this.
Thoughts?

A: There is no way to compare the expressions so the mock will always return null.
If this is just to test, in isolation, the flow of the method under test, you can use It.IsAny<Expression<Func<T, bool>>>() for the argument matcher.
public void Signup_Fail_DuplicateEmail_Controller_Test() {
    //Arrange
    var user = UserHelper.CreateSignupUser();
    user.Email = "duplicate@test.com";
    var uRepo = new Mock<IUserRepository>();

    uRepo
        .Setup(_ => _.GetSingle(It.IsAny<Expression<Func<T, bool>>>()))
        .Returns(user);

    var uc = new UserController(uRepo.Object);

    //Act
    var result = uc.Signup(user);

    //Assert
    var status = Assert.IsType<StatusCodeResult>(result);
    Assert.Equal(StatusCodes.Status409Conflict, status.StatusCode);
}

Reference Moq Quickstart
The above works well for testing expected behavior in isolated unit test.
If however you want to test the actual expression then that can be done using an in-memory integration test or an actual database.


text:
Q: gradle buildscript can't resolve objects defined in buildSrc I've created a new project in Android Studio and converted the gradle buildscript to use the kotlin dsl, like so:
build.gradle.kts (project)
buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:4.1.1")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.10")

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

tasks.register("clean", Delete::class) {
    delete(rootProject.buildDir)
}

build.gradle.kts (app)
plugins {
    id("com.android.application")
    kotlin("android")
}

android {
    compileSdkVersion(30)
    buildToolsVersion = "30.0.2"

    defaultConfig {
        applicationId = "com.myproject"
        minSdkVersion(16)
        targetSdkVersion(30)
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        named("release").configure {
            isMinifyEnabled = false
            proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.10")
    implementation( "androidx.core:core-ktx:1.3.2")
    implementation( "androidx.appcompat:appcompat:1.2.0")
    implementation( "com.google.android.material:material:1.2.1")
    implementation( "androidx.constraintlayout:constraintlayout:2.0.4")
    testImplementation( "junit:junit:4.+")
    androidTestImplementation( "androidx.test.ext:junit:1.1.2")
    androidTestImplementation( "androidx.test.espresso:espresso-core:3.3.0")
}

And finally, build.gradle.kts (BuildSrc)
import org.gradle.kotlin.dsl.`kotlin-dsl`

plugins {
    `kotlin-dsl`
}

repositories {
    jcenter()
}

dependencies {
    implementation(kotlin("script-runtime"))
}

This works and the project builds as expected.
Now I would like extract some of these hard-coded version numbers and names into constants. For example, I'd like to change this line:
implementation("org.jetbrains.kotlin:kotlin-stdlib:1.4.10")
to:
implementation("org.jetbrains.kotlin:${ProjectConfig.KOTLIN_VERSION}")
So I've created a new file at buildSrc/src/main/java/ProjectConfig.kt that looks like this:
object ProjectConfig {
    const val KOTLIN_VERSION:String = "1.4.10"
}

But when I try to reference this object from my gradle scripts and do a gradle sync, I get the following error:

e: E:\projects\MyProject\build.gradle.kts:11:58: Unresolved reference:
ProjectConfig

What is the proper way to define objects that can be referenced from all of my build.gradle files?

A: Here's what I found regarding availability of classes in the root build.gradle.kts:
On the root level:

*

*buildSrc classes: Available

*composite project classes: Available only if you declare a plugin from the composite project in the plugins {} block.

In the "buildscript" block:

*

*buildSrc classes: Available BUT if the class is in a package you must use the fully qualified class name e.g. com.example.MyClass (can't use import)

*composite project classes: Not available at all

This was determined with Gradle 7.


text:
Q: Migrate database oracle to postgresql : procedure we are going to migrate our database from Oracle to PostgreSQL.
I am new in PostgreSQL. We have a procedure like this:
CREATE OR REPLACE PROCEDURE USPX_TEST (NAME IN VARCHAR2,cb_results_cursor OUT SYS_REFCURSOR) IS
BEGIN
 OPEN cb_results_cursor FOR
          SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
END USPX_TEST;

Please provide me how to convert this same procedure in postgreSQL.
NOTE: we need to return the result in a cursor using out parameter
Thanks in advance...

A: To return a result in Postgres, you use a function, not a procedure:
CREATE OR REPLACE function USPX_TEST (NAME IN VARCHAR2)
  returns setof employees
as
$$
  SELECT * FROM EMPLOYEES WHERE EMP_NAME = NAME;
$$
language sql;

The use it like a table:
select *
from USPX_TEST('Zaphod');


text:
Q: Function in .JAR to load a file If I import a .jar into a Java project(Eclipse) in which there is a function using an IO and a File with a given path/name to load that file, and I call that function within a class in my project, where does the file have to be? Would it have to be in the .jar? In the project folder? The same folder as the .jar?

A: File represents a file in the filesystem.
If you don't use absolute paths, the path will be relative to the working directory of your application.
By default, the working directory of a Java application started as part of a Java project from Eclipse will be the root folder of that Java project. You can change it in the "Run" dialog options.
If you don't want to load from the filesystem, but from a resource contained within the Java project itself (so that it can be included in the jar file), you should not use File, but the classloader.


text:
Q: Javascript regex currency I'm trying to create a regex that meets the following conditions:

*

*0.01 - true

*01.01 - false

*122343.10 - true

*123,432.10 - false

*123 - false

*123423.1 - false

I've made the following but its not working as intended
^[0\.|1-9\d*\.]\d{2,2}$/

Using https://regexr.com/ to test

A: I would use this regex:
^(?!0\d)\d+\.\d{2}$

This uses a negative lookahead in the beginning to handle the requirement that the currency value can't start with zero, if another digit follows immediately afterward.
Demo
Here is another way of doing this:
^(?:0|[1-9]\d*)\.\d{2}$

This says to match a zero, followed by nothing by decimal point, or 1-9 if what follows is also another number before the decimal.

A: Tim Biegeleisen beat me by a few minutes, but here's another (less sophisticated) solution:
(^[0]|^[1-9]+)\.\d{2}$

https://regex101.com/r/QJ3YyQ/2
Edit: I just realized I missed an edge case. If the digits before the decimal point contained a zero, it wouldn't match.  Here's an updated regex:
(^[0]|^[1-9]\d*)\.\d{2}$

https://regex101.com/r/QJ3YyQ/4


text:
Q: Prawn - Rails 5.2 Put two bits of text on the same line but at either side I've been trying to replicate the text style in the following example:

But I havn't been able to find a way to put two text elements on the same line.
Is this possible with Prawn?  If so how does one do it?

A: You can use prawn-table, your image looks like a table with 2 columns.
https://github.com/prawnpdf/prawn-table
table([
  ["Base Price", "$275,99],
  ["Canary Cozy Sound Isolation Blankey", "$11.00"]
])

You will have to play, of course, with the style of the table to remove borders, the alignment of the cells for the second column, etc.


text:
Q: Angle of a triangle inscribed in a square Say we have a square $ABCD$. Put points $E$ and $F$ on sides $AB$ and $BC$ respectively, so that  $BE = BF$. Let $BN$ be the altitude in triangle $BCE$. What is $\angle DNF$?
I'm inclined to say that it's a right angle because that's what it looks like from what I've drawn, but I have no idea how to proceed.

A: $\angle DNF = 90^\circ \Longleftrightarrow \angle BNF = \angle CND$. It suffics to prove that $\triangle BNF \sim \triangle CND$.
Well, it's trivial:
$\angle NBF = \angle BEC = \angle NCD$ and $\displaystyle \frac{NB}{BF} = \frac{NB}{BE} = \sin\angle NEB = \cos\angle NCB = \frac{NC}{CB} = \frac{NC}{CD}$. Q.E.D

A:
Firstly We can write
(1) Oklid relation from $\triangle CNB$
$h^2=m(k+x)$
(2) Pisagor relation from $\triangle DPN$
$a^2=(x+k)^2+(x+k+m-h)^2$
(3) Pisagor relation from $\triangle FRN$
$b^2=h^2+k^2$
(4) Pisagor relation from $\triangle DCF$
$c^2=x^2+(x+k+m)^2$

if DNF triange is a right triangle,It must satisfy $a^2+b^2=c^2$.
$(x+k)^2+(x+k+m-h)^2+h^2+k^2=x^2+(x+k+m)^2$
$(x+k)^2+(x+k+m)^2-2h(x+k+m)+h^2+h^2+k^2=x^2+(x+k+m)^2$
$(x+k)^2-2h(x+k+m)+2h^2+k^2=x^2$
$xk+k^2-h(x+k+m)+h^2=0$
$xk+k^2-h(x+k+m)+m(k+x)=0$
$-h(x+k+m)+(k+m)(k+x)=0$
$\frac{x+k}{x+k+m}=\frac{h}{k+m}$
This result is equal to the rates of thales formula for similar triangles   $\triangle CRN \sim \triangle CBE$
Thus $a^2+b^2=c^2$  is correct for $\triangle DNF$ .

A: Let us do it through coordinate geometry. Let $B$ be the origin. Lets fix the coordinates first. $$A = (0,a)\\ B = (0,0) \\ C = (a,0)\\ D = (a,a)$$ Since $E$ and $F$ are equidistant from $B$, lets say $$F = (b,0)\\ E = (0,b)$$ where $0 \leq b \leq a$. The equation of the line $CE$ is $\dfrac{x}{a} + \dfrac{y}{b} = 1$. The equation of $BN$ is $y = \dfrac{a}{b}x$. This gives us the coordinate of $N$ as $\left( \dfrac{ab^2}{a^2 + b^2},\dfrac{a^2b}{a^2 + b^2} \right)$.
The slope of $FN$ is $m_1 = \dfrac{a^2b/(a^2+b^2) - 0}{ab^2/(a^2+b^2)-b} = \dfrac{a^2}{ab - a^2 - b^2}$.
The slope of $DN$ is $m_2 = \dfrac{a^2b/(a^2+b^2) - a}{ab^2/(a^2+b^2)-a} = \dfrac{ab - a^2 - b^2}{b^2 - a^2 - b^2} = - \left(\dfrac{ab-a^2-b^2}{a^2} \right)$.
Hence, the product of the slopes is $m_1m_2 = -1$. Hence your conjecture is indeed correct. I am waiting for someone to post a nicer geometric argument.

A: HINT: Try to resort to Homothetic transformation and you're done immediately.  Another way is to connect $N$ to the middle of the $DF$ (let's call that point $M$) and prove that you have there $NM$=$DM$=$MF$ (here you may resort to Apollonius' theorem). You also could resort to the cyclic quadrilaterals as another approaching way.


text:
Q: 1-Smoothness of the Symmetric Softmax Function Define the symmetric softmax of a vector $x\in \mathbb{R}^n$ to be
$$L(x)=\log\sum_i(e^{x_i}+e^{-x_i}).$$
Equation (6) in this paper states that for all $x$ and $y$
$$|\nabla L(x)-\nabla L(y)|_1 \leqslant ||x-y||_{\infty}.$$
(Apparently, this property is called 1-smoothness in optimisation)
I'm having a hard time proving this. I also tried to look for a proof but couldn't find one. I'd appreciate someone pointing me to a reference containing a proof. Thanks.

A: Edit: This question has been bugging my mind these days, to the extent that it forced me to start a bounty! Now if someone has any insights about this, please give it a try. I think I might have been on the right track, but now I'm lost.
$$L(x)=\log\sum_{i=1}^n(e^{x_i}+e^{-x_i})=\log 2+\log\sum_{i=1}^n\cosh x_i$$
Hence
$$\frac{\partial L}{\partial x_k}=\frac{\sinh x_k}{\sum_{i=1}^n\cosh x_i}$$
First we prove:
$$\Vert \nabla L(x)\Vert_1\le\Vert x\Vert_\infty$$
Knowing that $\Vert v\Vert_1=\sum|v_i|$ and $\Vert v\Vert_\infty=\sup|v_i|$, and also
$$\frac{\sinh z}{z}\le\cosh z,\; \forall z\in\mathbb R$$
we can write:
$$\begin{align}
\Vert \nabla L(x)\Vert_1=\sum_{k=1}^n\left|\frac{\partial L}{\partial x_k}\right|&=
\frac{\sum_{i=1}^n|\sinh x_i|}{\sum_{i=1}^n\cosh x_i}\\
&\le\frac{\sum_{i=1}^n|x_i|\cosh x_i}{\sum_{i=1}^n\cosh x_i}
\le\frac{\Vert x\Vert_\infty\sum_{i=1}^n\cosh x_i}{\sum_{i=1}^n\cosh x_i}\\&=\Vert x\Vert_\infty\end{align}$$
Now write $y=x+\delta$, you need to show that $\Vert\nabla L(x+\delta)-\nabla L(x)\Vert_1\le\Vert\delta\Vert_\infty$.
But... the statement seems a bit hard to prove, and I doubt that changing $y$ to $x+\delta$ will get us anywhere. By the way, regarding this question, I came up with something like this:
Let $p=\nabla L(x)$ and $q=\nabla L(y)$, and define:
$$M=\sum_{j=1}^n q_j\log p_j$$
then we have:
$$q_i-p_i=\frac{\partial M}{\partial x_i}$$
and we will need to show that $\Vert \nabla M\Vert_1\le\Vert y-x\Vert_\infty$. Although it seems $\Vert p\Vert_1\le\Vert x\Vert_\infty$ and $\Vert q\Vert_1\le\Vert y\Vert_\infty$ are some valuable information, but I wasn't able to go any further.

A: Here's an actual proof. It is inspired by one I found on page 116 of "First-Order Methods in Convex Optimization", although the book builds on a lot of theory that isn't really necessary when we are only interested in $L(x)$, so I cut out all of that and reduced it to the essential steps.
As the question notes, we are interested in proving 1-smoothness of the symmetric softmax. To that extent, first define in general terms what we mean by L-smoothness:
Definition ($L$-Smoothness, somewhat informal): Let $f: \mathbb{R}^n \to \mathbb{R}$ be some function and consider some norm $\lVert\cdot\rVert$ on $\mathbb{R}^n$. $f$ is $L$-smooth if it is differentiable and $\lVert \nabla f(x) - \nabla f(y)\rVert_* \le L \lVert x - y \rVert$, where $\lVert\cdot\rVert_*$ is the dual norm defined for the dual space ${\mathbb{R}^n}^*$ of $\mathbb{R}^n$ through $\lVert v \rVert_* = \max_x \{ \langle v, x \rangle \mid \lVert x \rVert = 1 \}$ for $v \in {\mathbb{R}^n}^*$.
Now in our case, $\lVert\cdot\rVert$ is the supremum norm, and its dual norm is the 1-norm, which shows that 1-smoothness is indeed the property we are interested in. We make use of the following lemma, proved at the end:
Lemma: If $f$ is convex, then $f$ is $L$-smooth if $\langle d, \nabla^2 f(x) \cdot d \rangle \le L \lVert d \rVert^2$ for all $d \in \mathbb{R}^n$.
(As an aside: The proof hence proceeds exactly as in this paper, Proposition 4, but with different norms)
To simplify the calculation, we will prove a stronger result, namely 1-smoothness of the unsymmetric softmax $S(x) = \log\left( \sum_i e^{x_i} \right)$, because as user24121 observes, we can always plug in $x = [x_1, \ldots, x_n, -x_1, \ldots, -x_n]$ to obtain the symmetric softmax. After some calculation, we see that the Hessian of $S$ is given by
$$
\nabla^2 S(x) = \mathrm{diag}(\sigma(x)) - \sigma(x)\sigma(x)^T
$$
where
$$
\sigma(x)_i = \frac{e^{x_i}}{\sum_j e^{x_i}}
$$
And now the computation is straightforward:
\begin{align}
d^T \nabla^2 S(x) d &= d^T \mathrm{diag}(\sigma(x))d - (\sigma(x)^Td)^2 \\
                    &\le d^T \mathrm{diag}(\sigma(x))d \\
                    &\le \lVert d \rVert_\infty^2 \lVert \sigma(x) \rVert_1 \le \lVert d \rVert_\infty^2
\end{align}

The only thing left to do now is to prove the lemma:
Proof of the Lemma: By Taylor's Theorem, for any $x, d \in \mathbb{R}^n$, there exists $\xi \in \mathbb{R}^n$ such that
$$
f(x + d) = f(x) + \nabla f(x)^T d + \frac12 d^T \nabla^2 f(\xi) d \overset{\text{assumption}}\le f(x) + \nabla f(x)^T d + \frac{L}{2} \lVert d \rVert^2
$$
We continue by proving that any $f$ satisfying the inequality is $L$-smooth. To do so, we must overcome the hurdle that we only have expressions of the form $\langle \nabla f(x + d), d \rangle$, but the definition of the dual norm requires the second argument to be independent of the first. To get around this, we take a detour via the Bregman distance:
Let $D_f(x, d) = f(x + d) - f(x) -  \nabla f(x)^T d \le \frac{L}{2}\lVert d \rVert^2$ (this is the Bregman distance, although we do not require $f$ to be strictly convex). Note that because $f$ is convex, $f(x + d) \ge f(x) + \nabla f(x)^Td$ and hence $D_f(x, d) \ge 0$ for all $d$. At the same time, for any $\delta \in \mathbb{R}^n$,
$$
  D_f(x, d + \delta) = f(x + d + \delta) - f(x) - \nabla f(x)^T (d + \delta)
$$
Bounding $f((x + d) + \delta)$ through the bound at the start of this proof yields
\begin{align}
  D_f(x, d + \delta) &\le f(x + d) - f(x) - \nabla f(x)^T (d + \delta) + \nabla f(x + d)^T \delta + \frac{L}{2}\lVert \delta \rVert^2 \\
&= D_f(x, d) + \langle \nabla f(x + d) - \nabla f(x), \delta \rangle + \frac{L}{2} \lVert \delta \rVert^2
\end{align}
Now with the very specific choice of $\delta = -\frac{\lVert \nabla f(x + d) - \nabla f(x) \rVert_*}{L} v$ for any $v \in \mathbb{R}^n$ with $\lVert v \rVert = 1$ and $\langle \nabla f(x + d) - \nabla f(x), v \rangle = \lVert \nabla f(x + d) - \nabla f(x) \rVert_*$, we can compute
\begin{align}
  0 &\le D_f(x, d + \delta) \le D_f(x, d) - \frac{\lVert \nabla f(x + d) - \nabla f(x) \rVert_*}{L} \langle \nabla f(x + d) - \nabla f(x), v \rangle + \frac{1}{2L} \lVert \nabla f(x + d) - \nabla f(x) \rVert_*^2 \\
&= D_f(x + d) - \frac{1}{2L} \lVert \nabla f(x + d) - \nabla f(x) \rVert_*^2
\end{align}
Hence
$$
\frac{1}{2L} \lVert \nabla f(x + d) - \nabla f(x) \rVert_*^2 \le D_f(x + d) \le \frac{L}{2} \lVert d \rVert^2
$$
Multiplying by $2L$ and taking the square root completes the proof.

A: So I've been messing around with this problem and I've made some progress, although I'm not at a full proof just yet. Maybe someone can pick up from here.
First, we notice that working with $L(x)=\log\sum_i e^{x_i}$ is without loss of generality since we can just plug in $[x^T, -x^T]^T$ and obtain the original softmax function.
For any $x,d \in \mathbb{R}^n$,
\begin{align*}
|\nabla L(x+d)-\nabla L(x)|_1 &= \sum_i \left| \frac{e^{x_i+d_i}}{\sum_j e^{x_j+d_j}}-\frac{e^{x_i}}{\sum_j e^{x_j}}\right|\\
&= \sum_i \left| \frac{\sum_je^{x_i+x_j+d_i}-\sum_je^{x_i+x_j+d_j}}{\sum_j \sum_k e^{x_j+x_k+d_j}}\right|\\
&= \frac{\sum_i \sum_j e^{x_i+x_j}|e^{d_i}-e^{d_j}|}{\sum_i \sum_je^{x_i+x_j}e^{d_i}}\stackrel{?}{\leqslant}||d||_{\infty}=:D.
\end{align*}
By the positivity of $e^{x_i+x_j}$, it suffices to show that $\sum_i \sum_j |e^{d_i}-e^{d_j}|-De^{d_i}\leqslant 0$ (i.e., $\sum_i \sum_j |e^{d_i}-e^{d_j}|-nD\sum_i e^{d_i}\leqslant 0$). At this point, we can assume without loss of generality that $d_1 \geqslant d_2 \geqslant \cdots \geqslant d_n$, then collect terms and simplify the left-hand side of the required inequality (specifically the double-sum) to:
\begin{align*}
\sum_i \sum_j |e^{d_i}-e^{d_j}|-nD\sum_i e^{d_i} &= \sum_k 2(n-2k+1)e^{d_k}-nD\sum_k e^{d_k}\\
&=\sum_k ((2-D)n-4k+2)e^{d_k}.
\end{align*}
If all coefficients of $e^{d_k}$ are non-positive, we are done. Otherwise, we define $k_0$ to be the largest index for which the corresponding coefficient is positive; i.e.,
$$k_0 = \left\lfloor \frac{(2-D)n+2}{4}\right\rfloor.$$
Then we can split the terms into ones with positive and nonpositive coefficients and say:
\begin{align*}
\sum_{k=1}^n ((2-D)n-4k+2)e^{d_k} \leqslant \left(\sum_{k=1}^{k_0} ((2-D)n-4k+2)\right)e^{d_1}+\left(\sum_{k=k_0+1}^{n} ((2-D)n-4k+2)\right)e^{d_n}.
\end{align*}
So the problem boils down to a condition on just two variables. After some massaging of the right-hand side, the condition to be shown is:
$$2k_0(n-k_0-0.5Dn)(e^{d_1}-e^{d_n})-Dn^2e^{d_n}\stackrel{?}{\leqslant}0.$$
This seems to check out empirically. We can also note that whenever $D\geqslant 2$, all coefficients are nonpositive, so we can restrict our search to $-2\leqslant d_n \leqslant d_1 \leqslant 2$.
That's as far as I've gotten. If someone has any ideas on how to prove this, it would be much appreciated.
EDIT: So here's what this looks like. It's maximised at $(d_1,d_n)=(0,0)$ with value $0$, and as you head towards $(-2,-2)$, it drops and then starts tending to zero again. This is for $n=2$ but it's pretty much the same for any $n$.

A: Here's another unfinished approach: We try to prove that for all $x, y \in \mathbb{R}^n$,
$$
\lVert \nabla L(x) - \nabla L(y) \rVert_1 \le \frac1n \lVert x - y \rVert_1 \le \lVert x - y \rVert_\infty
$$
where the last inequality is by p-norm relationships. That is, we reduce the question to showing that the gradient of $L$ is $\frac1n$-Lipschitz with respect to the 1-norm. To do this, we can compute the operator norm of the Hessian of $L$ because
$$
\lVert \nabla L(x) - \nabla L(y) \rVert_1 \le \frac1n \lVert x - y \rVert_1 \iff \sup_{x}\lVert \nabla^2 L(x) \rVert_1 \le \frac1n
$$
A proof sketch of this fact is at the the end of this post. Note that the L1 operator norm is just the maximum L1 norm of the rows ($\hat=$ columns because $\nabla^2 L$ is symmetric) of $\nabla^2 L$. After some calculation, we see that the 1-norm of the $i$-th row of the Hessian of $L$ is given by
$$
\lVert (\nabla^2 L(x))_{i,:} \rVert_1 = \frac{e^{x_i}}{S}\left(1 - \sigma_i - \sum_{j \ne i} |\sigma_j|\right) + \frac{e^{-x_i}}{S}\left(1 + \sigma_i + \sum_{j \ne i} |\sigma_j|\right)
$$
where
$$
S = \sum_j e^{x_j} + e^{-x_j} \qquad\qquad \sigma_j = \frac{e^{x_j} - e^{-x_j}}{S} \quad (j = 1, \ldots, n)
$$
So we can consider all $x_j$ except $x_i$ arbitrary but fixed, and maximise this expression with respect to $x_i$. If it ends up being at most $\frac1n$ then we are done. Note that
$$
\lim_{x_i \to \pm \infty} \lVert (\nabla^2 L(x))_{i,:} \rVert_1  = 0 \qquad \lVert (\nabla^2 L(\mathbf{0}))_{i,:} \rVert_1  = \frac1n
$$
which lends some (small amount of) credence to the idea that this approach might
work, but unfortunately maximising $\lVert (\nabla^2 L(x))_{i,:} \rVert_1$ is very painful.
Empirically it appears to hold at least for $n = 2$, but (again empirically) for any $x_j$ there is always an $x_i$ that makes it hold with equality, so there is no room for imprecision and hence probably no shortcut to maximising $\lVert (\nabla^2 L(x))_{i,:} \rVert_1$.

We want to prove that for any $f: \mathbb{R}^{n} \to \mathbb{R}^{n}$ and any norm $\lVert\cdot\rVert$,
$\lVert f(x) - f(y) \rVert \le C\lVert x - y\rVert \iff \sup_{x} \lVert Df(x) \cdot v \rVert \le C \lVert v \rVert$
for all $v \in \mathbb{R}^{n}$, where $Df(x)$ is the Jacobian of $f$ taken at point $x$.
The fundamental theorem of calculus provides
$$
  f(y) - f(x) = \int_{\theta = 0}^{1} Df(x_{\theta}) \cdot (y - x) d\theta \qquad x_{\theta} := x + \theta(y - x)
$$
For the first direction, observe that
$\lVert f(x) - f(y) \rVert \le C\lVert x - y\rVert$ implies that the directional derivative in every direction has norm at most $C$ (to see this,
write $y = x + \delta$, divide by $\lVert \delta \rVert$, and let $\delta \to \mathbf{0}$), and
hence clearly $\lVert Df(x) \rVert \le C$. For the second direction, the triangle
inequality (applied using Riemann sums and taking the limit) gives
$$
  \lVert f(y) - f(x) \rVert = \left\Vert \int_{\theta = 0}^{1} Df(x_{\theta}) \cdot (y - x) d\theta \right\Vert \le \int_{\theta = 0}^{1} \lVert Df(x_{\theta}) \cdot (y - x) \rVert d\theta \le \int_{\theta = 0}^{1} C \lVert y - x \rVert d\theta = C \lVert x - y \rVert
$$


text:
Q: Docker setup on WSL for pushing ACI containers I'm using docker on the windows subsystem for linux, and running into issues pushing containers to azure.  It seems there is more than one way to run docker in on WSL and neither works quite the way I need it to.
In both cases, I have Docker Desktop installed in Windows and set up properly for WSL usage.
Option 1: use the docker-ce package.  With this option I can run docker compose locally and run my containers.  However, docker login azure fails to launch a browser instance and wants to connect to local url "//azure/v2/".
Option 2: remove docker-ce and use the symlinks dropped by Docker Desktop.  Here I can successfully authenticate to azure, and push a simple container, but docker compose up returns this message:
ERROR: The platform targeted with the current context is not supported.
Make sure the context in use targets a Docker Engine.

Also, this option prevents me from running the containers locally- there is no dockerd running and service docker start says dockerd doesn't exist.
Now that I'm authenticated with Azure, if I reinstall docker-ce and run docker compose up in an ACI context, I see a new error:
cannot use ACI volume, required driver is "azure_file", found ""

What is the recommended setup for Docker on WSL that will enable me to push containers to ACI and also launch them locally?  What steps should I take to get the system into a clean state?

A:
What is the recommended setup for Docker on WSL that will enable me to
push containers to ACI and also launch them locally? What steps should
I take to get the system into a clean state?.

Assuming you are using WSL (ubuntu 18.04 version).
Please follow thease below steps to install docker and create container locally and push to ACI as well.
Step 1: Install Docker on Ubuntu 18.04
apt install docker.io

Step 2  : Pull Images from Docker Hub
docker pull nginx.
Step 3 : Make local conatainer and open at port 5000(default port is 80)
docker container run -d --name nginx --publish 5000:80 nginx

Step 4: login in azure
az login

Step 5 : Created Container Registry
az acr create -g "v-rasXXXXX" -n "TestMyAcr90" --sku Basic --admin-enabled true

Step 6 : Tag docker images
docker tag 605c77e624dd testmyacr90.azurecr.io/my_nginx

Where 605c77e624dd is IMAGE ID of nginx.
you can check images using cmdlet docker images.

Step 7 : Now login into conatainer registry using docker.
docker login testmyacr90.azurecr.io

Step 8 :  Push docker images into container registry
docker push testmyacr90.azurecr.io/my_nginx

Step 9: Create container Instance from Container Registry Image
az container create --resource-group v-rXXXXXdtree --name mycontainer90 --image testmyacr90.azurecr.io/my_nginx:latest --cpu 1 --memory 1 --registry-login-server testmyacr90.azurecr.io --registry-username TestMyAcr90 --registry-password CipBd5joXXXXXXfZrbw/Pl --dns-name-label testnginx5 --ports 80

You can take reference of this thread which i have answered few month back


text:
Q: Como puedo hacer MODIFY a una columna usando Python + SQL aloha, estoy tratando de hacer ALTER TABLE MODIFY a una columna, ponerle INT y AUTOINCREMENT pero me da este error de sintaxis, YA NO tengo mente para solucionarlo.

File "c:\Users\Eilienz13\OneDrive\Escritorio\py_conexion\main.py", line 54, in  modificarColumnas() File "c:\Users\Eilienz13\OneDrive\Escritorio\py_conexion\main.py", line 45, in modificarColumnas cursor.execute(query) psycopg2.errors.SyntaxError: error de sintaxis en o cerca de «MODIFY» LINE 1: ALTER TABLE clientes MODIFY COLUMN id INTEGER AUTOINCREMENT...

aqui parte del codigoo donde esta el conflicto
def crearTabla():
    cursor = connection.cursor()
    query = "Create Table clientes(id int,nombre varchar(255),telefono numeric(12),cuenta varchar(255),contraseña varchar(255),usuario varchar(255),pin numeric(4),inicio date,fin date, PRIMARY KEY (id)"
    try:
        cursor.execute(query)
    except:
        print("La tabla clientes ya existe duh, no te repitas mas ;)")
    cursor.close()

def modificarColumnas():
    cursor = connection.cursor()
    query = ' ALTER TABLE clientes MODIFY COLUMN id INTEGER AUTOINCREMENT '
    cursor.execute(query)
    print("Columna Actualizada")
    cursor.close

A: MODIFY no es una instrucción de SQL para hacer lo que quieres; se utiliza ALTER.
ALTER TABLE clientes ALTER COLUMN id TYPE INTEGER AUTOINCREMENT


text:
Q: Send E-Mails using javascript within a domain What is the safest and most elegant way to send a E-Mail from javascript within a domain?
We have our own mail server and I'm trying to avoid 3rd party API's as smtpjs or emailjs.
Is this possible?

A: You can't send email via JavaScript alone. You can either open the mail client on the users device via window.open('mailto:{{to_address}}'), or by calling an API that's hosted on a server (Using nodejs with mandrill would work for this). For an example on how to do that, there's a pretty exhaustive code sample here.

A: In nodejs you can use nodemailer to connect your email server and send emails.
Here is a sample code to do that (from Nodemailer's Docs):
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function main() {
  // Generate test SMTP service account from ethereal.email
  // Only needed if you don't have a real mail account for testing
  let testAccount = await nodemailer.createTestAccount();

  // create reusable transporter object using the default SMTP transport
  let transporter = nodemailer.createTransport({
    host: "smtp.ethereal.email",
    port: 587,
    secure: false, // true for 465, false for other ports
    auth: {
      user: testAccount.user, // generated ethereal user
      pass: testAccount.pass, // generated ethereal password
    },
  });

  // send mail with defined transport object
  let info = await transporter.sendMail({
    from: '"Fred Foo " <foo@example.com>', // sender address
    to: "bar@example.com, baz@example.com", // list of receivers
    subject: "Hello ✔", // Subject line
    text: "Hello world?", // plain text body
    html: "<b>Hello world?</b>", // html body
  });

  console.log("Message sent: %s", info.messageId);
  // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

  // Preview only available when sending through an Ethereal account
  console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
  // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
}

main().catch(console.error);


text:
Q: mdadm shows inactive raid0 array instead of degraded raid6 after disk failure I've been running an Ubuntu 18.04 system with an 8-disk raid 6 array, that crashed while having a faulty disk (I only noticed that there was a faulty disk after the crash). The raid array has survived multiple Ubuntu installs, so it's not the first time I've had a faulty disk and usually I keep the array running until I've received a replacement disk, but this time I can't get it running again (my plan was to first get it running again, and only order the replacement when I'm sure that the array is recoverable).
I've disconnected the faulty drive and the other 7 drives still seem to be operating, mdadm however seems to think that those 7 drives are part of a raid 0 array instead of a raid 6 array. So at the moment, I'm not courageous enough to try anything that might be destructive without at least trying to get some confirmation that there's a bigger chance of working than destroying data (I've
 made intermittent backups over the years, but there's probably some photos on there that haven't been backed up yet... and yes I know I need a better backup strategy, and as always it'll be the first thing I'll do after this problem is either fixed or conclusively unfixable).
When I run mdadm --assemble --scan I get the following output:
mdadm: /dev/md127 assembled from 7 drives - not enough to start the array while not clean - consider --force.

I would try the --force option, but the output of mdadm --detail /dev/md127 is as follows:
/dev/md127:
           Version : 1.2
        Raid Level : raid0
     Total Devices : 7
       Persistence : Superblock is persistent

             State : inactive
   Working Devices : 7

              Name : Ares:RaidStorage  (local to host Ares)
              UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
            Events : 1627931

    Number   Major   Minor   RaidDevice

       -       8       32        -        /dev/sdc
       -       8        0        -        /dev/sda
       -       8      112        -        /dev/sdh
       -       8       80        -        /dev/sdf
       -       8       48        -        /dev/sdd
       -       8       16        -        /dev/sdb
       -       8       96        -        /dev/sdg

And since mdadm --assemble --help says that --force involves modifying superblocks I'm afraid that running --force will overwrite the superblocks with the info for a raid 0 array.
I've let mdadm examine the member devices and they still all think they're part of an 8-disk raid 6 array (which I hope means there's still a chance of recovery):
root@Ares:/# for i in a b c d f g h; do mdadm --examine /dev/sd$i; done
/dev/sda:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : 1e104c8a:529eb411:a7fd472a:5854d356

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : 712f8115 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 0
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdb:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : d3bb43b7:9f39be47:102328fa:2bab3f5e

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : ab7d4456 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 2
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdc:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : 325a0adf:3d917a47:977edea3:db21d42a

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : 494b0c89 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 1
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdd:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : 6c0200a0:37b50833:683a868b:ebfb9e94

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : 47416ea1 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 3
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdf:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : b91d04d3:3f1508ad:687bb30f:7d6fc687

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : 6b999e8b - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 4
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdg:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1960 sectors, after=944 sectors
          State : active
    Device UUID : 64ba7519:7d47e97c:21c5622a:18df9eca

    Update Time : Fri Mar  1 21:50:02 2019
  Bad Block Log : 512 entries available at offset 72 sectors
       Checksum : df7c2710 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 5
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdh:
          Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
     Array UUID : 8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1
           Name : Ares:RaidStorage  (local to host Ares)
  Creation Time : Mon Jun 25 18:19:09 2012
     Raid Level : raid6
   Raid Devices : 8

 Avail Dev Size : 5860531120 (2794.52 GiB 3000.59 GB)
     Array Size : 17581590528 (16767.11 GiB 18003.55 GB)
  Used Dev Size : 5860530176 (2794.52 GiB 3000.59 GB)
    Data Offset : 2048 sectors
   Super Offset : 8 sectors
   Unused Space : before=1968 sectors, after=944 sectors
          State : active
    Device UUID : 493cfa55:b00800db:40c8fbc4:c94dabbb

    Update Time : Fri Mar  1 21:50:02 2019
       Checksum : 5b4dbb3 - correct
         Events : 1627931

         Layout : left-symmetric
     Chunk Size : 512K

   Device Role : Active device 6
   Array State : AAAAAAA. ('A' == active, '.' == missing, 'R' == replacing)

For completeness sake here's also the output of some other commands that are probably relevant:
root@Ares:/# mdadm --examine --scan
ARRAY /dev/md/RaidStorage  metadata=1.2 UUID=8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1 name=Ares:RaidStorage

root@Ares:/# cat /proc/mdstat
Personalities : [linear] [multipath] [raid0] [raid1] [raid6] [raid5] [raid4] [raid10]
unused devices: <none>

root@Ares:/# cat /etc/mdadm/mdadm.conf
# mdadm.conf
#
# !NB! Run update-initramfs -u after updating this file.
# !NB! This will ensure that initramfs has an uptodate copy.
#
# Please refer to mdadm.conf(5) for information about this file.
#

# by default (built-in), scan all partitions (/proc/partitions) and all
# containers for MD superblocks. alternatively, specify devices to scan, using
# wildcards if desired.
#DEVICE partitions containers

# automatically tag new arrays as belonging to the local system
HOMEHOST <system>

# instruct the monitoring daemon where to send mail alerts
MAILADDR root

# definitions of existing MD arrays
ARRAY /dev/md/RaidStorage  metadata=1.2 UUID=8f7270c4:ec9e19f5:afa4d7c7:2fcb1ee1 name=Ares:RaidStorage

# This configuration was auto-generated on Mon, 01 Oct 2018 20:35:13 +0200 by mkconf

To exclude the possibility of some configuration being wrong in my Kubuntu installation, I've also tried mdadm --assemble --scan from a Kubuntu USB-stick, but that had the exact same effect as running it from my normal install.
So my questions are as follows:

*

*how is it possible that all drives think they're part of my 8-disk raid 6 array, but mdadm --assemble --scan still results in an inactive raid 0 array?

*can I safely call mdadm --assemble --scan     --force?

*If no on 2: how can I convince mdadm to see my 7 disks as part of an 8-disk raid 6?

A: This worked for me:

*

*go into /etc/mdadm/mdadm.conf

*edit the line for your array and add in raid level and disk numbers.
Mine was
level=raid6 num-devices=6

obviously you'd need to say 8 devices:)
Looks like my system massively overheated – two boxes in a tight space and disks went nuts. One disk dropped out, which I thought was screwing it up, and another just disappeared, but when I checked the events I had 5 disks with the same and the first one to drop out was behind.
After setting mdadm.conf, I restarted the system and checked all the disks were detected then the assemble command needed the --force option (scary), but worked ok and started checking itself. Then added back in the first disk to drop out and it looks like it just updated it and it's all clean now.


text:
Q: Twilio Sending multiple sms on same number instead of multiple numbers Hello i am using twilio in my project builted on laravel framework. Its stated in twilio site that "For sending sms to multiple number you need to add all numbers in an array and make seperate call for each number using iteration". I am doing the same but its till sending multiple message to only first number instead of sending sms to multiple numbers. here is my code.
foreach ($numbers as $number) {
Twilio::sms(['to' => [$number],'message' => 'Hi']);
 }

$numbers Contains two numbers +9234222***** and +9231102***** But i am recieving two messages on +9234222***** instead of one on each. And in my twilio dashboard its showing 2 segments for +9234222***** and +9231102***** is not there.
UPDATE
I have found the solution for sending same message to multiple numbers . for sending sms to multiple numbers simply pass the array $numbers in 'to' instead of loop. Twilio::sms(['to' => $numbers,'message' => 'Hi']);
Still waiting for best answer.
What if i want to send message with Name. e.g 'Hi John' on +9234222***** and 'HI Doe' on +9231102*****.
Note: I am using https://github.com/j42/laravel-twilio

A:
UPDATE I have found the solution for sending same message to multiple
  numbers . for sending sms to multiple numbers simply pass the
  array $numbers in 'to' instead of loop. Twilio::sms(['to' => $numbers,'message' => 'Hi']);
Still waiting for best answer. What if i want to send message with
  Name. e.g 'Hi John' on +9234222***** and 'HI Doe' on +9231102*****


text:
Q: Restoring postgres sql file over 20gb We have a backup of a database with sql 32gb format (containing various binary files over 50mb), but when we do import data only 8gb are actually placed on the bench.
We've done everything from changing the version that was Postgres 8.3 to Postgres 9.1 and even then not everything is imported.

A: It could be normal for Postgres.
When you export your binary data to sql file it must be encoded as base64 and properly escaped. This encoding and escaping can increase the size of the output file 2-6 times (from my experience). + sql dump format adds overhead for INSERT/COPY commands.
Try dumping the base in binary format, to see what size would the binary dump be.


text:
Q: center linearlayout verticall android Have this code, a scrollview.. a relativelayout and inside it linearlayout..
Problem is at some devices the page takes half the screen size. in other pages it goes to scroll mode.
i want in cases it takes half screen, to center linearlayout vertically

    <?xml version="1.0" encoding="utf-8"?>
     <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
      <LinearLayout
        android:id="@+id/linear1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:gravity="center_vertical"
        android:orientation="vertical" >

A: okay try this, if it works for you, I've set it centerInParent , so scrollView exactly in center

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="#ccc"
    android:gravity="center"
    android:padding="15dp" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" >

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

//PUT YOUR STUFF HERE

        </LinearLayout>
    </ScrollView>

</RelativeLayout>


text:
Q: Fishy glGetAttribLocation returns -1 I'm trying to use a shader program that consists of two shaders.
Ortho.vert:
uniform vec2 ViewOrigin;
uniform vec2 ViewSize;

in vec2 Coord;

void main ()
{
  gl_Position = vec4((Coord.x - ViewOrigin.x) / ViewSize.x,
                     1.0f - (Coord.y - ViewOrigin.y) / ViewSize.y,
                     0.0f, 1.0f);
}

Tiles.frag:
uniform sampler2D Texture;
uniform sampler2D LightMap;

in vec2 TextureCoord;
in vec2 LightMapCoord;

void main ()
{
  vec4 textureColor  = texture2D(Texture, TextureCoord);
  vec4 lightMapColor = texture2D(LightMap, LightMapCoord);

  gl_FragColor = vec4(textureColor.rgb * lightMapColor.rgb, 1.0f);
}

glGetAttribLocation is returning -1 for TextureCoord and LightMapCoord. I've read about instances where the compiler optimizes away attributes that aren't used, but in this example you can see that they are clearly used. Is there something about the OpenGL state (glEnable, etc.) that is required in order to enable samplers? I'm not sure what else could be wrong here. Any help is appreciated.

A: Attributes cannot go directly into the fragment shader. Their full name is vertex attributes, which means that they provide values per vertex, and are inputs to the vertex shader.
Fragment shaders can have in variables, but they do not correspond to vertex attributes. They need to match up with out variables of the vertex shader.
So what you need to do to get this working is to define the attributes as inputs to the vertex shader, and then pass the values from the vertex shader to the fragment shader. In the vertex shader, this could look like this:
uniform vec2 ViewOrigin;
uniform vec2 ViewSize;

in vec2 Coord;
in vec2 TextureCoord;
in vec2 LightMapCoord;

out FragTextureCoord;
out FragLightMapCoord;

void main ()
{
    gl_Position = vec4((Coord.x - ViewOrigin.x) / ViewSize.x,
                       1.0f - (Coord.y - ViewOrigin.y) / ViewSize.y,
                       0.0f, 1.0f);
    FragTextureCoord = TextureCoord;
    FragLightMapCoord = LightMapCoord;
}

Then in the fragment shader, you declare in variables that match the out variables of the fragment shader. These variables will receive the per-fragment interpolated values of the what you wrote to the corresponding out variables in the vertex shader:
uniform sampler2D Texture;
uniform sampler2D LightMap;

in vec2 FragTextureCoord;
in vec2 FragLightMapCoord;

void main ()
{
    vec4 textureColor  = texture2D(Texture, FragTextureCoord);
    vec4 lightMapColor = texture2D(LightMap, FragLightMapCoord);

    gl_FragColor = vec4(textureColor.rgb * lightMapColor.rgb, 1.0f);
}

Having to receive the attribute values in the vertex shader, and explicitly passing the exact same values through to the fragment shader, may look cumbersome. The important thing to realize is that this is just a special case of a much more generic mechanism. Instead of simply passing the attribute value directly to the out variable in the vertex shader, you can obviously apply any kind of computation to calculate the values of the out values, which is often necessary in more complex shaders.


text:
Q: How to intuitively see that the $\text{volume of a pyramid }= 1/3 \times (\text{ area of base}) \times (\text{height})$ I'm interested to know if anyone can point me to a non-calculus way of seeing that the $\text{volume of a pyramid} = \frac{1}{3}\times(\text{area of base})\times(\text{height})$. Yes, I've googled.

A: I actually find it easiest to take a cube and divide it into 6 pyramids: just connect all of the corners of a cube to the midpoint, and for each of the 6 faces of the cube, you get a pyramid having that face as its base. If the cube has a side length s, then each pyramid has an s by s base and height s/2, and its volume is 1/6 the volume of the cube, which is 1/3 base times height.

A: The easiest intuitive one I know is to take a cube and divide it into three pyramids.  Take one corner and form the pyramid with each of the three faces that don't touch that corner.  They are congruent, so have volume 1/3*base*height as the base is a square the side of the cube and the height is the side of the cube as well.  Then appeal to affine transformations to say this applies to all pyramids.

A: Proof:
Put together 6 pyramids to make a cube. You will see that volume of whole cube can be considered as sum of 2 equal smaller volumes (area by half-height of cube). Its also the height of pyramid multiplieds by area. The small volume is also the sum of 3 pyramids, because 3 is half of 6. So single pyramid is 1/3rd of this multiplication.

A: Carrying off on Gabe's answer I would like to add a little bit of detail:
Quick summary:
You have 6 pyramids in a cube.
Cube details:
The base of the cube = $\textrm{s} \cdot \textrm{s} = \textrm{s}^2$
The height of the cube = s
The volume of the cube = $\textrm{s} \cdot \textrm{s} \cdot \textrm{s} = \textrm{s}^3$
Square-based pyramid details:
The base of each square pyramid is the same as the base of the cube = $\textrm{s} \cdot \textrm{s} = \textrm{s}^2$
The height of each pyramid is half the height of the cube = $\frac{\textrm{s}}{2}$
The volume of the square-based pyramid is as mentioned 1/6 the cube = $\frac{\textrm{s}^{3}}{6}$
Solving:
Now if we cut the cube in half at the midpoint from the top of the cube we can isolate one of the pyramids inside the half cube.
Volume of half cube = length $\cdot$ width $\cdot$ height = $\textrm{s} \cdot \textrm{s} \cdot \frac{\textrm{s}}{2} = \frac{\textrm{s}^{3}}{2}$
Now to find the volume of the pyramid:
$$\frac{\textrm{s}^{3}}{2} -  \frac{\textrm{s}^{3}}{6} = \frac{\textrm{s}^{3}}{3}$$
Hope this helped.


text:
Q: jquery pass 2 ajax result outside ajax I have a simple working ajax with result.
   jQuery.ajax({
        type: "POST",
        url: my_url_query
        success:function(response){
        }

    }).done(function(response) {

        //Assuming the response for currChild1 is 12
        res1 = response;
        window.$vars = { currChild1: res1 };
        window.$vars = { currChild2: res2 };    //----> How will I do this

        $.getScript( "assets/js/main/request_add_staff.js");
    });

Is it posible to create another ajax to pass another vars to the getscript

A: Anyway I think This is what im looking..
 async:false

kinda long code.
but if you have an idea to shorten this... that will do.
jQuery.ajax({
    type: "POST",
    url: "index.php/form_dashboard/get/Senior/"+ dataid,
    success:function(response){

    },

    error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
    },
    async:false

}).done(function(response) {
    res_Senior = response;
});

//Result for Junior
jQuery.ajax({
    type: "POST",
    url: "index.php/form_dashboard/get/Junior/"+ dataid,
    success:function(response1){

    },

    error:function (xhr, ajaxOptions, thrownError){
        alert(thrownError);
    },
    async:false

}).done(function(response1) {
    res_Junior = response1;
});

window.$vars = { currChild: res_Senior, currChildJunior: res_Junior };

$.getScript( "assets/js/main/request_add_staff.js");


text:
Q: CSS: % sizes in width and height in menus with images I have a site which should be suitable for mobile visitors, and therefore should scale to the dimensions of the user's screen, both in width and height. Furthermore, I have 2 navigation menus (1 left, 1 right), and some fixed info on the bottom (like a footer). All these parts contain images that should be scaled to fit into the menu's dimensions. Concretely, the page is something like (adding a random image that is too big by default):

      Middle content

With the following CSS:
.wholepage {
  width: 100%;
  height: 100%;
}

.wholepage img {
  width: 100%;
  height: 100%;
}

.top {
  height: 80%;
}

.left, .right {
  width: 15%;
}

.middle {
  width: 70%;
}

.bottom {
  height: 20%;
}

Like that, the width of the page adapts itself perfectly, sticking to the 15%-70%-15% distribution between left-middle-right. However, vertically, all the images refuse to scale. How can I get the page to fit to the 80%-20% distribution for top-bottom?
EDIT: Here's a way to see it, if you fill this in in http://www.w3schools.com/css/tryit.asp?filename=trycss_default

Middle content

Thanks!

A: Don't use width & height, just use max-width:
.wholepage img {
  max-width: 100%;
}

IE < 8 scales images poorly and to get good quality scaling you need to use AlphaImageLoader with the SizingMethod set to scale. Probably the easiest way to do that is with Drew Diller's DD_BelatedPNG library. Be aware there are performance implications to using the AlphaImageLoader. Also, IE6 doesn't support max-width so use width: 100% in a conditional comment if you need to support IE6.
Also, I can say enough about Ethan Marcotte's A List Apart Article on Responsive Design (which is an excerpt from also excellent his book.)

A: First; don't use tables for styling. Use divs, or even better the html5 tags like  and  and such.
To ensure correct handling of height with percentages, you should set html and body to 100% height as well, like:
html, body { height: 100%; }

A: I ended up hacking it. Unless someone knows a better way, here's what I did:
function fixHorizontalDimension(){
  maxHeight = window.innerHeight * [% height desired] * 0.9;
  imgs = document.getElementsByClassName([classname of wrongly sized objects]);
  for(i=0; i<imgs.length; i++){
    imgs[i].style.height = maxHeight;
  }
}

Since the site is only to be used personally, and using a mobile browser, this fix does the job. Resizing (e.g. switching from portrait to landscape) doesn't work though.


text:
Q: Nutch - Getting Error: JAVA_HOME is not set. when trying to crawl First and foremost I'm a Nutch/Hadoop newbie. I have installed Cassandra. I have installed Nutch on the Master node of my EMR cluster. When I attempt to execute a crawl using the following command:
sudo bin/crawl crawl urls -dir crawl -depth 3 -topN 5

I get
Error: JAVA_HOME is not set.

If I run the command without 'sudo' I get:
    Injector: starting at 2014-07-16 02:12:24
Injector: crawlDb: urls/crawldb
Injector: urlDir: crawl
Injector: Converting injected urls to crawl db entries.
Injector: org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/home/hadoop/apache-nutch-1.8/runtime/local/crawl
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:197)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:208)
    at org.apache.hadoop.mapred.JobClient.writeOldSplits(JobClient.java:1081)
    at org.apache.hadoop.mapred.JobClient.writeSplits(JobClient.java:1073)
    at org.apache.hadoop.mapred.JobClient.access$700(JobClient.java:179)
    at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:983)
    at org.apache.hadoop.mapred.JobClient$2.run(JobClient.java:936)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:415)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1190)
    at org.apache.hadoop.mapred.JobClient.submitJobInternal(JobClient.java:936)
    at org.apache.hadoop.mapred.JobClient.submitJob(JobClient.java:910)
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1353)
    at org.apache.nutch.crawl.Injector.inject(Injector.java:279)
    at org.apache.nutch.crawl.Injector.run(Injector.java:316)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
    at org.apache.nutch.crawl.Injector.main(Injector.java:306)

I cannot figure this out. I've seen the other forum here: Similar Topic
and followed it to no avail. I have added
export JAVA_HOME=/usr/lib/jvm/java-7-oracle

and
export PATH=$PATH:${JAVA_HOME}/bin

to my ~/.bashrc and I am using Linux..
Any help will be appreciated!!

A: The problem is I was running
sudo bin/crawl crawl urls -dir crawl -depth 3 -topN 5

I used
bin/crawl ./urls/seed.txt TestCrawl http://localhost:8983/solr/ 5

And all is well, just a malformed command.. i.e. 'crawl' is deprecated as stated here: Apache Nutch Tutorial


text:
Q: Invalid type and ID field error Good day,
I"m trying to write this class. But I'm getting an:

"Invalid type:Occurence__c"

error. Also it's showing invalid ID field: myOcc.
Can't figure out what I'm missing, please assist.
Here is the code:
public class OccurenceCalculatorTEMPORARY {

        public static void calculateOcc(List<Occurrence__c> myOcc)
        {
            List<Claim__c> AllClaimsLinkedToOccurrence  = new List<Claim__c>();
            AllClaimsLinkedToOccurrence = [Select Name, Initial_estimate__c from Claim__c where Occurrence__c = 'myOcc'];

            //set Claim Value to 0
            Decimal TotalClaimValue=0;

            For(Claim__c Item: AllClaimsLinkedToOccurrence)
            {
                TotalClaimValue = TotalClaimValue + Item.Initial_estimate__c;
            }
            system.debug(TotalClaimValue);

                For(Claim__c Item: AllClaimsLinkedToOccurrence)
                {
                    Item.Excess__c = (Item.Initial_estimate__c/TotalClaimValue) * Item.Policy_Excess__c;
                    Item.Captive_Stop_Loss_Estimate_Override__c = (Item.Initial_estimate__c/TotalClaimValue) * Item.Stop_Loss_Limit__c;

                }

            update AllClaimsLinkedToOccurrence;
        }
}

A: It is clear the custom field Occurrence__c is missing in your query
[Select Name, Initial_estimate__c from Claim__c where Occurrence__c = 'myOcc'];

Please include the custom field in this Query hopefully it will resolve your issue.
[Select Name, Initial_estimate__c,Occurrence__c from Claim__c where Occurrence__c = 'myOcc'];


text:
Q: Is there a difference between a button being deactived and disabled? I am writing requirements and in order to prevent any conceptual confusions I want to make sure, the term I use is aligned with technical perspective. Is there a difference between a button being deactive and disabled technically?

A: Technically it should be disable as usually you disable a button  not deactivate it.
Deactivate may also mean that you are destroying the button while disable means that you are just not enabling the normal functioning of the button.

A: Activate/Deactivate is mostly used for an Account/Feature not for the button, Buttons can be enabled/disabled for activating or deactivating a feature or an account.

A: In technical perspective there isn't anything called button being deactive, we can only enable/disable or show/hide a button. To prevent any confusion during design and implementation, you should use Enable/Disable for a button.


text:
Q: Does Composer prioritise private packages' requirements? I have a project where composer is used to install Nette Framework and one private package hosted in private composer repository.
Project's composer.json:
...
"require": {
    "php": ">= 5.3.7",
    "nette/nette": "2.1.*",
    "myrepo/private-package": "*"
},
"minimum-stability": "dev",
"repositories": [
    {
        "type": "composer",
        "url": "http://myrepo.org"
    }
]
...

Private package's composer.json:
...
"require": {
         "php": ">= 5.3.7",
         "nette/nette": "2.2.*"
},
...

As you can see the project requires Nette 2.1.*. The Private package, however, requires Nette on version 2.2.*.
If I run composer install, Composer installs 2.2.* version of Nette. That doesn't comply the project's composer.json (which requires 2.1.*).
I understand both requirments can't be fulfilled. But why composer doesn't print out an error then? Do private repositories have some kind of priority?

A: This was a bug and is now fixed.


text:
Q: How to edit classes in tempus-dominus (datetimepicker) not shown in the source file? I would like to change for instances the class .day of tempus-dominus (https://tempusdominus.github.io/bootstrap-4/) but even when using !important it does not seem to work when inspecting (try not to click around because the inspecting of it is weird. Even when forcing :hover the dropdown disappears).
Let's say I want to change the font-size of .day from 90% to 100%
Source code: https://tempusdominus.github.io/bootstrap-4/theme/css/tempusdominus-bootstrap-4.css
Find the code below =)
Thanks in advance for your help!
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Tempus Dominus</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="" />
<meta name="keywords" content="" />

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/github.min.css" />
<link rel="stylesheet" href="https://tempusdominus.github.io/bootstrap-4/theme/css/tempusdominus-bootstrap-4.css" />

          <input type="text" class="form-control datetimepicker-input" id="datetimepicker5" data-toggle="datetimepicker" data-target="#datetimepicker5" />

A: In order to debug the plugin you can add a debugger call like:
$('#datetimepicker5').on('hide.datetimepicker', function(e) {
     $('#datetimepicker5').datetimepicker('show');
     debugger;
});

If you need to change the font-size for all cells with the class day You can:
.bootstrap-datetimepicker-widget table td.day {
    font-size: 80%;
}

$('#datetimepicker5').datetimepicker();

$('#datetimepicker5').on('show.datetimepicker', function(e) {
    //$('#datetimepicker5').datetimepicker('show');
    //debugger;
});
.bootstrap-datetimepicker-widget table td.day {
  font-size: 80%;
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" >
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.1/css/tempusdominus-bootstrap-4.min.css" />

            <input type="text" class="form-control datetimepicker-input" id="datetimepicker5" data-toggle="datetimepicker" data-target="#datetimepicker5" />


text:
Q: How to configure Sublime Text 2 editor for easier working with ATK4 framework? How to configure Sublime Text 2 editor for easier working with ATK4 framework?
I'm interested in some standard macros (snippets) for page, view, model files and maybe some more Sublime Text 2 editor configuration details useful for developing in ATK4.

A: I had two and I've contributed them into atk4/tools folder. You can found them here:
https://github.com/atk4/atk4/tree/master/tools
Feel free to contribute more!

A: I cannot find any plugins for ATK4. You could make requests for plugins on the ST2 UserEcho and see if you get any bites.


text:
Q: What are these characters Ö and Þ supposed to be and how do I configure firefox to load them properly? tl;dr: My internet browser is not configured properly so characters are not loading properly. I am using the default Firefox 24.0 in Linux Mint 16, and have not installed any typesetting software. I am doing a math test and I am getting unusual characters. Ö and Þ are being displayed, but I think a √ and ⇒ should be displayed instead, respectively. What do I need to install to get these to load properly.
I know very little typesetting software and I am technologically inept.
I am currently doing an online math test. There are four tests that I need to do. If I exit the test, it will automatically submit whatever answers I have selected.
The test I am doing right now is a very easy basic algebra test, about middle school level. All the questions on it are true or false questions. To illustrate how easy the test is supposed to be, the first question is asking if the following statement is true or false:
a/(a/b) = a/b
After this, I am getting unusual characters in the questions:
|-7|=Ö49=7
Ö8-Ö29=Ö(-21)
Ö8-Ö29=-Ö21
3x=6 Þ x=2
(x-2)(x+2) = 1 Þ x-2 = 1 or x+2 = 1
Based on how they are being used, I assume Ö should be a √, and that Þ should be a ⇒
Am I correct?
What do I need to install to get these to display properly on future tests? The course's section on the university website does not specify what needs to be installed, but it recommend using Internet Explorer or else there's a chance that "fonts will not load properly".
I asked this in tex but they sent me here.
Unfortunately, I cannot link the problem page as only people in my program can view it.


text:
Q: Order array by predefined rules I have an array of currencies ["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"]. I would like to order it by moving predefined list if the currency is present to the beginning of array. Predefined list is ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'].
So in this case it should return ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP', 'SEK', BGN'].
But in case unfiltered array does not contain all values in predifined list it should also order it correctly. For example : ["GBP", "EUR", "NOK", "LTU", "ZGN"] should look like ['EUR', 'NOK', 'GBP', 'LTU', 'ZGN'
I was trying to sort it using this function:
list.sort(c => ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'].indexOf(c))

but it puts all predefined currencies at the end of the list, not at the from. Maybe there is a better way of doing that?

A: You could use sorting with map and a hash table for the sort order. If the value is not in the hash table, the original order is taken.

var order = ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'],
    orderObj = Object.create(null),
    data = ["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"];

// generate hash table
order.forEach((a, i) => orderObj[a] = i + 1);

// temporary array holds objects with position and sort-value
var mapped = data.map((el, i) => { return { index: i, value: orderObj[el] || Infinity }; });

// sorting the mapped array containing the reduced values
mapped.sort((a, b) => a.value - b.value || a.index - b.index);

// assigning the resulting order
var data = mapped.map(el => data[el.index]);

console.log(data);

A: I guess this can also be achieved like this

Array.prototype.intersect = function(a) {
  return this.filter(e => a.includes(e));
};
Array.prototype.excludes = function(a) {
  return this.filter(e => !a.includes(e));
};
var getCur = (p,c) => p.intersect(c).concat(c.excludes(p)),
      cur1 = ["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"],
      cur2 = ["GBP", "EUR", "NOK", "LTU", "ZGN"],
       pdl = ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP', 'SEK', 'BGN'];
console.log(getCur(pdl,cur1));
console.log(getCur(pdl,cur2));

A: here is my solution. :-)

//custom index of
Array.prototype.customIndexOf = function(a){
  return this.indexOf(a) === -1 ? Infinity : this.indexOf(a);
}

let orderArr = ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'];

/*test case 1*/
let urList = ["GBP", "EUR", "NOK", "DKK", "SKE", "USD", "SEK", "BGN"];
urList.sort((a, b) => { return orderArr.customIndexOf(a) - orderArr.customIndexOf(b); });
console.log(urList); //[ 'EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP', 'SEK', 'BGN' ]

/*test case 2*/
let newList = ["GBP", "EUR", "NOK", "LTU", "ZGN"];

newList.sort((a, b) => { return orderArr.customIndexOf(a) - orderArr.customIndexOf(b); });
console.log(newList); //[ 'EUR', 'NOK', 'GBP', 'LTU', 'ZGN' ]

hope this is what u need :-)

A: var tabCurrency = ['GBP', 'EUR', 'NOK', 'DKK', 'SKE', 'USD', 'SEK', 'BGN'];
var tabPredef = ['EUR', 'USD', 'DKK', 'SKE', 'NOK', 'GBP'];
var newTabGood = [];
    tabPredef.forEach(function (itemPredef, indexPref) {

         var indexTemp;

         tabCurrency.forEach(function (itemCurrency, indexCurrency) {
               if(itemPredef == itemCurrency)
               {
                  newTabGood.push(itemPredef);
                  indexTemp = indexCurrency;
               }
         })

         tabCurrency.splice(indexTemp, 1)
   })

 var resultat = newTabGood.concat(tabCurrency);

 console.log(resultat)


text:
Q: What are the different LWC's for Uploading Files? I have seen developers using two different components (both LWC I think) for uploading.
Differences:

*

*Control 1

*

*Button text is Select Files

*Control 2

*

*Button text is Upload Files

*After choosing a file, it shows a red button: Delete File

However, I can only find one Upload control here in SalesForce docs

A: They are lightning-file-upload and lightning-input type="file". The former uploads files and has a UI, the latter only selects files, and you can read those files through JavaScript.


text:
Q: What is the fastest way to manipulate large csv files in Python? I have been working on a python code, which reads a csv file with 800 odd rows and around 17000 columns.
I would like to check each entry in the csv file and see if this number is bigger than or smaller than a value, if it is, I assign a default value. I used pandas and worked with dataframes, apply and lambda functions. It takes me 172 minutes to finish going through all entries in the csv file. Is it normal? Is there any faster way to do this?. I am using Python 2.7. I don't know if it helps, but I am running it on a windows 10 machine with 32GB ram. Thanks in advance for the help.
The code is attached below.

def do_something(some_dataframe):
    col = get_req_colm(some_dataframe)
    modified_dataframe = pd.DataFrame()
    for k in col:
        temp_data = some_dataframe.apply(lambda x: check_for_range(x[k]), axis=1).tolist()
        dictionary = {}
        dictionary[str(k)] = temp_data
        temp_frame = pd.DataFrame(dictionary)
        modified_dataframe = pd.concat([modified_dataframe, temp_frame], axis=1)
    return modified_dataframe

def check_for_range(var):
    var = int(var)
    try:
        if var == 0:
            return 0
        if var == 1 or var == 4:
            return 1
        if var == 2 or var == 3 or var == 5 or var == 6:
            return 2
    except:
        print('error')

def get_req_colm(df):
    col = list(df)
    try:
        col.remove('index/Sample count')
        col.remove('index / Sample')
        col.remove('index')
        col.remove('count')
    except:
        pass
    return col

df_after_doing_something = do_something(some_dataframe)
df_after_doing_something.to_csv(output_folder + '\\df_after_doing_something.csv', index=False)

A: using pandas,for cvs data, makes it efficient. but your code is not efficient.it will be faster if you try code given blow.
def do_something(some_dataframe):
    col = get_req_colm(some_dataframe)
    col = col.to_numpy()
    np_array = np.zeros_like(col)
    for i in range(len(col)):
        k = np_array[i]
        temp_data = np.zeros_like()
        temp_data[k == 1 or k == 4] = 1
        temp_data[k == 2 or k == 3 or k == 5 or k == 6] = 2
        np_array[i] = k
    modified_dataframe = pandas.Dataframe(np_array)
    return modified_dataframe

def get_req_colm(df):
    col = list(df)
    try:
        col.remove('index/Sample count')
        col.remove('index / Sample')
        col.remove('index')
        col.remove('count')
    except:
        pass
    return col

it will work perfectly and don't forget to import numpy.
import numpy as np

if you didn't get this go and check some numpy tutorial and do it then. the link given below will help you otherwise
Replacing elements in a numpy array when there are multiple conditions