text:
Q: OpenCV Video Capture not working for Android | Kivy, Buildozer I am building an App which got several video filters. But the App is not working on Android cause =>  capture = cv.VideoCapture(0) doesnt get access to the android camera.
The Code below shows how i edit the Video footage of the App at the moment. On PC it works perfect. But after building it, it shows no
video footage on android
Buidlozer Spec got permission btw..

capture = cv.VideoCapture(0)

class BinaryCam(Image):

    def on_kv_post(self, base_widget):
        #self.capture = cv.VideoCapture(0)
        # cv.namedWindow("CV2 Image")
        Clock.schedule_interval(self.update, 1.0 / 33.0)

    def update(self, dt):
        # display image from cam in opencv window
        ret, frame = capture.read()

        if ret==True:

            # cv.imshow("CV2 Image", frame)
            gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
            # convert it to texture
            adaptive_thresh = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY, 11, 3)

            buf1 = cv.flip(adaptive_thresh, 0)
            buf = buf1.tobytes()
            texture1 = Texture.create(size=(adaptive_thresh.shape[1], adaptive_thresh.shape[0]),
                                      colorfmt='luminance')  # in grayscale gibts kein bgr
            # if working on RASPBERRY PI, use colorfmt='rgba' here instead, but stick with "bgr" in blit_buffer.
            texture1.blit_buffer(buf, colorfmt='luminance', bufferfmt='ubyte')  # replacing texture
            # display image from the texture
            self.texture = texture1

Or maybe is there a way to get the Camera Frames from the Kivy Camera and edit them with OpenCV.
But i really would prefer this method i showed here with OpenCV.
Thank you


text:
Q: asp.net UserControl click event to run a function i have a asp.net webform app with employees.aspx and a user control usercontrol1.ascx  as follows
employees.aspx
i have placed usercontrol1.ascx inside my employees.aspx and i need to run a function get_employees() which is inside employees.aspx
usercontrol1.ascx
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="usercontrol2.ascx.vb" Inherits="wogapp.usercontrol1" %>
<asp:Button ID="btnEmpDetails" runat="server" Text="Employee Details"  class="btn btn-primary" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: copy else statement to if statement I am trying to copy the code of else state to the if statement.
In here I see if-eqz as the if condition but I don't know where the else condition is here. Can someone help me find else condition so that I can copy it to become the if code also.
I also want to know where is the start and the end of the else statement body
if-eqz v1, :cond_1

.line 103
:goto_1
return-object v0

.line 82
:cond_0
invoke-static {}, Landroid/os/Environment;->getExternalStorageDirectory()Ljava/io/File;

move-result-object v0

invoke-virtual {v0}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

move-result-object v0

.line 83
new-instance v2, Ljava/lang/StringBuilder;

invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V

invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v0

const-string v2, "/Android/data/"

invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v0

sget-object v2, Lcom/lingren/game/MonoJavaHelper;->s_Application:Landroid/app/Application;

invoke-virtual {v2}, Landroid/app/Application;->getPackageName()Ljava/lang/String;

move-result-object v2

invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v0

const-string v2, "/files/Res/AssistObj/"

invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v0

invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object v0

.line 84
const-string v2, "MonoJavaHelper"

new-instance v3, Ljava/lang/StringBuilder;

invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

const-string v4, "ExternalStorageState Not UseAble:"

invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v3

invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v1

invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

move-result-object v1

invoke-static {v2, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

goto :goto_0

.line 95
:cond_1
:try_start_1
invoke-virtual {p0}, Landroid/app/Activity;->getApplicationContext()Landroid/content/Context;

move-result-object v1

invoke-virtual {v1}, Landroid/content/Context;->getFilesDir()Ljava/io/File;

move-result-object v1

invoke-virtual {v1}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

move-result-object v0

.line 96
new-instance v1, Ljava/lang/StringBuilder;

invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

invoke-virtual {v1, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v1

const-string v2, "/Res/AssistObj/"

invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

move-result-object v1

invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
:try_end_1
.catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0

move-result-object v0

goto :goto_1

A: Your example seems incomplete. For example it has goto :goto_0 but doesn't contain the :goto_0 label. In any event, the following example should help you to figure out how to handle your case. Smali code like the following:
if-nez v0, :cond_0

const-string v2, "hello 1"

:goto_0
return-void

:cond_0
const-string v2, "hello 2"
goto :goto_0

Corresponds to Java code like:
if (i == 0) {
    s = "hello 1";
}
else {
    s = "hello 2";
}
return;

The exact placement of goto statements and branches depends on compiler. Also for different conditions you may see if-nez or if-eqz or some other statements.


text:
Q: Tensorflow optimizer with negative feedback? I am optimizing a tensorflow model.  It is not a neural net, I am just using tensorflow for easy derivative computations.  In any case, it seems that loss surface has a steep edge somewhere, and my loss will sometimes "pop out" of the local minimum it is currently targeting, the loss will go up a great deal, and the optimizer will go gallivanting off after some other optimum elsewhere.
I want it to not do that thing.  Specifically, I want it to look at the loss, be all like "holy crap that just went up a whole bunch, I'd better backtrack a bit."  Even though the current gradient may want to send it off elsewhere, I want it to "go back" in sense, and continue trying to find the optimum it was previously targeting.  Is there a tensorflow optimizer that has some kind of "negative feedback" in this way?

A: You may do a forward pass, check the loss, and then do backward if you think the loss is acceptable. In TF 1.x it requires some tf.cond and manual calculation and application of gradients. The same in TF 2.0 only the control flow is easier, but you have to use gradient_tape and still apply gradients manually.


text:
Q: How to resolve blank errors for Xampp phpMyAdmin and MySQL Several problems with phpmyAdmin running on Windows 7 in Xampp.
Creating a new database or editing data within a table, creates a network error message, with the response code being:
{"reload_flag":"1","success":false,"error":""}
Same response code when trying to load the second page of tables, the first page is just loaded again.
When changing a field in the database a blank notification popup is shown:
Updating a field
Initially MySQL table crashed errors were logged in the event viewer. The error was the 'MySQL table has crashed' and the tables in question were: procs_priv, tables_priv, columns_priv, and db. these errors are no longer being logged, yet we're having the same issues as before.
I've tried uninstalling and reinstalling Xampp, re importing the database and then repairing all tables. Non of this had any effect so far.

A: reload_flag is returned in auth() function. It looks like I solved this error by clearing cookies and/or switching between different auth_type(http, cookie, config) in config.inc.php file


text:
Q: How can I duplicate a point with matrix rotation every iteration? I have this code :

X1 = 0.5;
X2 = 0.3;
Y1 = 0.1;
Y2 = 0.4;

for(int i =0;i<20;i++) // let's suppose that we need to create 19 points from point A

{
    point1 = new System.Windows.Point((float)X1 , (float)Y1 );
    point2 = new System.Windows.Point((float)X2 , (float)Y2 );

    System.Windows.Point RotatedPoint = p1 * rotmatrix;
    System.Windows.Point RotatedPoint2 = p2 * rotmatrix;

    DrawingVisual d = new DrawingVisual();

    System.Windows.Media.Pen pen = new System.Windows.Media.Pen();

    DrawingContext drawingContext = d.RenderOpen();

    pen.Brush = System.Windows.Media.Brushes.Black;

    drawingContext.DrawLine(pen, point1 , point2 );

    drawingContext.DrawLine(pen, RotatedPoint, RotatedPoint2);

    drawingContext.Close();
    canvas.Children.Add(new VisualHost { Visual = d });
}

I would like to create a new point from original point with rotate it , as an example :
Let's suppose that I have a point called A , what I need exactly is created B, C and D ...

*

*B is the result point of A rotation .

*C is the result point of B rotation .

How can I do this?


text:
Q: How to set ui minimal view in safari in ios with brim I am using brim to set a minimal-ui view in safari of iPhone 6 S.
I want to enter into minimal-ui view mode when swiping up the page, but the only way to do that is to rotate the screen. My page doesn't have offset to do a scroll.
I am searching in the library a method to have the minimal view on the screen, but I don't find it.
https://github.com/gajus/brim

A: It seems not possible to enter in minimal-u view calling some javascript method because safari doesn't allow it. The alternative solution to enter this mode is to inform the user to do some action like swipe up or rotate the device.


text:
Q: Detecting tap gesture that is not on a UISubView I have three UIButton instances: buttonA, buttonB and buttonC. Each button has its own center and occupies a certain size.
I want these buttons to "do something" (i.e. have the alpha values change) when the the screen is tapped anywhere except for where the buttons are, such that one can pressed the buttons to have their actions triggered without "doing this something" happening.
What's the best way to go about this, please?

A: Try something like this:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Get location of touch
    let pos = touches.first?.location(in: self.view)

    if !b.frame.contains(pos) && !b2.frame.contains(pos) && !b3.frame.contains(pos) {
        // Change alpha or do something else
    }
}

Where b, b2, and b3 are each of your buttons.

A: This works like any other tap. Just give the "elsewhere" (e.g. the view controller's main view) a UITapGestureRecognizer and respond when the user taps it. It won't be triggered when you tap one of the buttons, because in that case the button will eat the tap.


text:
Q: How can i generate random DNS names of Hosts in java this could be of the form:
aaa1.bbb2.ccc3.ddd4
Maybe taking a cue from http://www.dnsjava.org/download/
and first generating individual strings aaaa1 , bbb2 etc and then using join()
or
String validCharacters = $('a', 'z').join() + $('A', 'Z').join();

String randomString(int length) {
    return $(validCharacters).shuffle().slice(length).toString();
}

@Test
public void buildFiveRandomStrings() {
    for (int i : $(5)) {
        System.out.println(randomString(12));
    }
}

A: Just generate 2, 3 or more valid random strings that would represent subdomain(s) and domain.
Maybe then randomly pick a tld (.com,.net,.gov....) and then join them all with "." separator. Shouldn't be to hard.


text:
Q: Sort list of strings and give preference to string more closer to start index Creating a web-component that shows results as you type. Currently I have list of string like:
[
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
]

To search when the user type 'B', currently I'm getting results as:
'Aaeaca Bi',
'Aegaca Bd',
'Biah gi',
'dBciag ch'

but I want:
'Biah gi',
'dBciag ch',
'Aegaca Bd',
'Aaeaca Bi',

I want to get search results giving preference to result which is more closer to start index.
How do I solve the problem?

A: Sort by the difference in the indexOf of the string to find in the array item:

const arr = [
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
  'xxxx',
];
const strToFind = 'B';
const result = arr
  .filter(str => str.includes(strToFind))
  .sort((a, b) => a.indexOf(strToFind) - b.indexOf(strToFind))
console.log(result);

It probably doesn't matter in this situation (for a given piece of code, performance rarely does), but you could decrease the computational complexity to O(n) rather than O(n log n) by using counting sort rather than the built-in .sort.
If you want search to be case-insensitive, turn the initial array into one whose items contain both the lowercase version and the original version, then perform operations by checking the lowercase version, and map to the original version at the end:

const arr = [
  'Aaeaca Bi',
  'Aegaca Bd',
  'Biah gi',
  'dBciag ch',
  'Ghiad dl',
  'xxxx',
  'aabaa'
];
const casedArr = arr.map(str => [str.toLowerCase(), str]);
const strToFind = 'B'.toLowerCase();
const result = casedArr
  .filter(([str]) => str.includes(strToFind))
  .sort((a, b) => a[0].indexOf(strToFind) - b[0].indexOf(strToFind))
  .map(([, origCasedStr]) => origCasedStr);
console.log(result);


text:
Q: Why isn't there a typeclass for functions? In a learning problem I've been messing around with, I realised I needed a typeclass for functions with operations for applying, composing etc. Reasons...

*

*It can be convenient to treat a representation of a function as if it were the function itself, so that applying the function implicitly uses an interpreter, and composing functions derives a new description.

*Once you have a typeclass for functions, you can have derived typeclasses for special kinds of functions - in my case, I want invertible functions.
For example, functions that apply integer offsets could be represented by an ADT containing an integer. Applying those functions just means adding the integer. Composition is implemented by adding the wrapped integers. The inverse function has the integer negated. The identity function wraps zero. The constant function cannot be provided because there's no suitable representation for it.
Of course it doesn't need to spell things as if it the values were genuine Haskell functions, but once I had the idea, I thought a library like that must already exist and maybe even using the standard spellings. But I can't find such a typeclass in the Haskell library.
I found the Data.Function module, but there's no typeclass - just some common functions that are also available from the Prelude.
So - why isn't there a typeclass for functions? Is it "just because there isn't" or "because it's not so useful as you think"? Or maybe there's a fundamental problem with the idea?
The biggest possible problem I've thought of so far is that function application on actual functions would probably have to be special-cased by the compiler to avoid a looping problem - in order to apply this function I need to apply the function application function, and to do that I need to call the function application function, and to do that...
More Clues
Example code to show what I'm aiming for...
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}

--  In my first version, Doable only had the one argument f. This version
--  seemed to be needed to support the UndoableOffset type.
--
--  It seems to work, but it also seems strange. In particular,
--  the composition function - a and b are in the class, but c isn't,
--  yet there's nothing special about c compared with a and b.
class Doable f a b where
  fwdApply :: f a b -> a -> b
  compDoable :: f b c -> f a b -> f a c

--  In the first version, I only needed a constraint for
--  Doable f a b, but either version makes sense.
class (Doable f a b, Doable f b a) => Undoable f a b where
  bwd      :: f a b -> f b a

  bwdApply :: f a b -> b -> a
  bwdApply f b = fwdApply (bwd f) b

--  Original ADT - just making sure I could wrap a pair of functions
--  and there were no really daft mistakes.
data UndoableFn a b = UFN { getFwd :: a -> b, getBwd :: b -> a }

instance Doable UndoableFn a b where
  fwdApply = getFwd
  compDoable f g = UFN ((getFwd f) . (getFwd g)) ((getBwd g) . (getBwd f))

instance Undoable UndoableFn a b where
  bwd f    = UFN (getBwd f) (getFwd f)
  bwdApply = getBwd

--  Making this one work led to all the extensions. This representation
--  can only represent certain functions. I seem to need the typeclass
--  arguments, but also to need to restrict which cases can happen, hence
--  the GADT. A GADT with only one constructor still seems odd. Perhaps
--  surprisingly, this type isn't just a toy (except that the whole thing's
--  a toy really) - it's one real case I need for the exercise. Still a
--  simple special case though.
data UndoableOffset a b where
  UOFF :: Int -> UndoableOffset Int Int

instance Doable UndoableOffset Int Int where
  fwdApply (UOFF x) y = y+x
  compDoable (UOFF x) (UOFF y) = UOFF (x+y)

instance Undoable UndoableOffset Int Int where
  bwdApply (UOFF x) y = y-x
  bwd (UOFF x) = UOFF (-x)

--  Some value-constructing functions
--  (-x) isn't shorthand for subtraction - whoops.
undoableAdd :: Int -> UndoableFn Int Int
undoableAdd x = UFN (+x) (\y -> y-x)

undoableMul :: Int -> UndoableFn Int Int
undoableMul x = UFN (*x) (`div` x)

--  With UndoableFn, it's possible to define an invertible function
--  that isn't invertible - to break the laws. To prevent that, need
--  the UFN constructor to be private (and all public ops to preserve
--  the laws). undoableMul is already not always invertible.
validate :: Undoable f a b => Eq a => f a b -> a -> Bool
validate f x = (bwdApply f (fwdApply f x)) == x

--  Validating a multiply-by-zero invertible function shows the flaw
--  in the validate-function plan. Must try harder.
main = do putStrLn . show $ validate (undoableAdd 3) 5
          putStrLn . show $ validate (undoableMul 3) 5
          --putStrLn . show $ validate (undoableMul 0) 5
          fb1 <- return $ UOFF 5
          fb2 <- return $ UOFF 7
          fb3 <- return $ compDoable fb1 fb2
          putStrLn $ "fwdApply fb1  3 = " ++ (show $ fwdApply fb1  3)
          putStrLn $ "bwdApply fb1  8 = " ++ (show $ bwdApply fb1  8)
          putStrLn $ "fwdApply fb3  2 = " ++ (show $ fwdApply fb3  2)
          putStrLn $ "bwdApply fb3 14 = " ++ (show $ bwdApply fb3 14)

The application involves a kind of unification where unified values aren't equal, but are related via those invertible functions - Prolog-style logic but with a = f(b) constraints rather than a = b. Most of the composition will result from optimizing a union-find structure. The need for inverses should be obvious.
If no item in a unified set has an exact value, then a particular item can only be quantified relative to another item in that unified set. That's why I don't want to use "real" functions - computing those relative values. I could drop the whole function aspect and just have absolute and relative quantities - I probably only need numbers/vectors and (+) - but my inner architecture astronaut wants his fun.
The only way I break the links apart again is via backtracking, and everything is pure - union-find will be done using keys into an IntMap as "pointers". I have simple union-find working, but as I haven't added the invertible functions yet, there's no point listing it here.
Reasons I can't use Applicative, Monad, Arrow etc
The main operations I need the function abstraction class to provide are application and composition. That sounds familiar - e.g. the Applicative (<*>), Monad (>>=) and Arrow (>>>) are all composition functions. However, the types that implement the function abstraction in my case will contain some data structure that represents a function, but which isn't (and can't contain) a function, and which can only represent some limited set of functions.
As I mentioned in the explanation of the code, sometimes I can only quantify one item relative to another because no item in a "unified" cluster has an exact value. I want to be able to derive a representation of that function, which in general will be the composition of several provided functions (walking up to a common ancestor in the union/find tree) and of several inverse functions (walking back down to the other item).
Simple case - where the original "functions" are limited to integer-offset "functions", I want the composed result as an integer-offset "function" - add the component offsets. That's a big part of why the composition function needs to be in the class as well as the application function.
This means I cannot provide the operations pure, return or arr for my types, so I can't use Applicative, Monad or Arrow.
This isn't a failure of those types - it's a mismatch of abstractions. The abstraction I want is of a simple pure function. There's no side-effecting, for example, and no need to build a convenient notation for sequencing and composing the functions other than an equivalent of the standard (.) that applies to all functions.
I could instance Category. I'm confident that all my functiony-things will be able to provide an identity, though I probably don't need it. But as Category doesn't support application, I'd still need a derived class anyway to add that operation.

A: As you point out, the main problem with using Applicative here is that there is no sensible definition for pure. Hence, Apply was invented. At least, that's my understanding of it.
Unfortunately, I do not have examples on hand of instances of Apply that aren't also Applicative. It is claimed this is true for IntMap, but I have no idea why. Similarly, I don't know whether your example - offset integers - admits an Apply instance.

A: Well, I don't know of any baked in ideas that market themselves as representing "function-y" things. But there are several that come close
Categories
If you have a simple function concept that has identities and composition, than you have a category.
class Category c where
  id :: c a a
  (.) :: c b c -> c a b -> c a c

The disadvantage is that you cannot create a nice category instance with a set of objects (a, b, and c). You can create a custom category class I suppose.
Arrows
If your functions have a notion of products and can inject arbitrary functions, than arrows are for you
 class Arrow a where
   arr :: (b -> c) -> a b c
   first :: a b c -> a (b, d) (c, d)
   second :: a b c -> a (d, b) (d, c)

ArrowApply has a notion of application which looks important for what you want.
Applicatives
Applicatives have your notion of application, I've used them in an AST to represent function application.
class Functor f => Applicative f where
  pure :: a -> f a
  (<*>) :: f (a -> b) -> f b -> f c

There are many other ideas. But a common theme is to build up some data structure representing your function, and than pass it to an interpretation function.
This also how many free monads work. I'd suggest poking at these if you're feeling brave, they're a powerful tool for the stuff that you're suggesting and essentially let you build up a datastructure using do notation and then collapse it into a side effecting computation with different functions. But the beauty is that these functions just operation on the datastructure, and aren't really aware of how you made it all. This is what'd I'd suggest for your example of an interpreter.

A: In addition to the mentioned Category, Arrow, and Applicative:
I've also discovered Data.Lambda by Conal Elliott:

Some function-like classes, having lambda-like construction

Looks interesting, of course, but difficult to understand without examples...
Examples
Examples can be found in the wiki-page about tangible values (TV) who seem to be one of the things that caused the creation of TypeCompose library; see Inputs and function-valued outputs.
The TV library's idea is to display Haskell values (including functions) in a tangible manner.
To follow the StackOverflow rule about not posting bare lonks, I copy some bits below which should give the idea of these things:
The first example reads:
apples, bananas :: CInput Int
apples  = iTitle "apples"  defaultIn
bananas = iTitle "bananas" defaultIn

shoppingO :: COutput (Int -> Int -> Int)
shoppingO = oTitle "shopping list" $
            oLambda apples (oLambda bananas total)

shopping :: CTV (Int -> Int -> Int)
shopping = tv shoppingO (+)

which gives when run as runIO shopping (see there for more comments, GUIs, and more examples):
shopping list: apples: 8
bananas: 5
total: 13


text:
Q: Finding the dependence of maximum vertex degree on k-colorability How do we describe a construction of a 2-colorable graph where the degree of every vertex is greater than or equal to (|V|-1)/2? Based on that, what can be said about the dependence of maximum vertex-degree on k-colorability of a graph?
My first thought is that in order for a vertex to connect to every single other vertex on a graph, it's degree would have to be |V|-1. But since we're looking at half of that in (|V|-1)/2, it would only be connected to half the vertices in the graph, so if this was the case for all vertices in G we'd be constructing a 2-colorable bipartite graph (is my thought).
I'm not too sure how to deal with the second part, however. I know that in a graph there can be n different colors for k given n vertices in a row and we need to add colors whenever there are adjacent vertices, but I can't figure out how the maximum vertex-degree in particular effects how many colors we can use for a graph.

A: A complete bipartite graph where one side has $\lceil\frac{|V|}{2}\rceil$ vertices and the other side has $\lfloor\frac{|V|}{2}\rfloor$ vertices, is 2-colorable and meets the desired lower bound on the minimum degree.
So a graph may have very large minimum degree $D$ and be $k$-colorable for some $k <<D$--as the above example illustrates. But all graphs with maximum degree $D-1$ are $D$-colorable. In fact, all graphs $G$ with no $D$-core i.e., there is no subgraph of $G$ where every vertex has degree at least $D$--are also $D$-colorable.


text:
Q: How to mention two aggregation functions in the same query? I have an sql query to get information from three different tables as following:
select users.username, users.id, users.avatar, users.daily_tahmin, users.alert, f1.comments_no, f2.tahmins_no, f3.monthly_tahmins_no from users LEFT join
(SELECT count(comments) AS comments_no, user_id
 FROM comments
  Where user_id = 12
) AS f1  on users.id = f1.user_id  left join
(
  SELECT count(tahmin) AS tahmins_no, user_id
  FROM tahminler
  Where user_id = 12
) AS f2 on users.id = f2.user_id left join
(
  SELECT count(tahmin) AS monthly_tahmins_no, user_id, matches_of_comments.match_id
  FROM tahminler
    INNER JOIN matches_of_comments on tahminler.match_id = matches_of_comments.match_id
  Where user_id = 12 AND (MONTH( STR_TO_DATE( matches_of_comments.match_date,  '%d.%m.%Y' ) ) =  '01' AND YEAR( STR_TO_DATE( matches_of_comments.match_date,  '%d.%m.%Y' ) ) =  '2014')
) AS f3 on users.id = f3.user_id
where users.id = 12

and it gives the following result :
+------------+----+----------------+--------------+-------+-------------+------------+--------------------+
|  username  | id |     avatar     | daily_tahmin | alert | comments_no | tahmins_no | monthly_tahmins_no |
+------------+----+----------------+--------------+-------+-------------+------------+--------------------+
| cold heart | 12 | 1389002263.jpg |            0 |     0 |          65 |        258 |                 10 |
+------------+----+----------------+--------------+-------+-------------+------------+--------------------+

The previous code was not optimized after i do some EXPLIAN and I tried to optimized it and I got the following query:
SELECT m.*,count(comments.id)
FROM comments
JOIN
(SELECT users.username, users.id, users.avatar, users.daily_tahmin, users.alert
FROM users
WHERE id=12)as m ON m.id = comments.user_id

My problem is that I can not get (tahmins_no,monthly_tahmins_no) every time i add them to the query it gives wrong result I can not find a way to add them correctly to the query to be in optimized way?? can I have any advice from anybody here?

A: Your simplified query is:
select m.*, count(c.id)
from comments c join
     users m
     on m.id = c.user_id
where m.id = 12
group by m.id;

You should be able to add in the monthly number:
select m.*, count(c.id), f3.*
from comments c join
     users m
     on m.id = c.user_id join
     (select count(tahmin) AS monthly_tahmins_no, user_id, moc.match_id
      from tahminler t join
           matches_of_comments moc
           on t.match_id = moc.match_id
      Where user_id = 12 AND
            MONTH( STR_TO_DATE( moc.match_date,  '%d.%m.%Y' ) ) = 1 AND
            YEAR( STR_TO_DATE( moc.match_date,  '%d.%m.%Y' ) ) =  2014
     ) f3
     on f3.user_id = m.id
where m.id = 12
group by m.id;

The month() and year() function return numbers, not strings.  I don't understand why the field match_date would be stored as a string -- seems like a silly choice for a column whose name contains date.


text:
Q: How to write lines (for loop) with specific format with different variables in python (mix between string and integers ) in Python I would like to write the following lines as it is but with different variables (a,z and g) as the following:
For i In {1:a+1}
b~{i} = z+(i-1)*g;
EndFor
I mean I have a code defines the a,z,g (but they might be different each time): I do not want python to calculate the loop, I just wanna the above lines to be written with same (loop format) in a text file
here as the code I think .. any suggestion or documentation to help me ...
Not sure how could I write what i want with different variables
import numpy as np
a=3
z=5
g=2
fileID                                =    open(output.dat,"w")
fileID.write('%s%s%d%s%d%s%d%s%d%s \n'%
 ('Point(1)=','{',0,',',0,',',a,',',z,'}'))
 fileID.write('\n')
 # I NEED TO WRITE HERE the following for loop but with different a, z and g ?
For i In {1:a+1}
b~{i} = z+(i-1)*g;
EndFor

Thanks,

A: Try this
import numpy as np
a=3
z=5
g=2
fileID = open('output.dat',"w")
s = "For i In {1:"+str(a)+"+1}\n\t"+str(z)+"~{i} = z+(i-1)*"+str(g)+";\nEndFor"
fileID.write(s)
fileID.close()


text:
Q: Two Loops at almost the same time i don't what this process is called, but i've seen that it's possible.
what is this process called?
basically,  i have a method that has a loop, and in every iteration has a delay second.
function myLoop(float delay)
{
    for(int x=0; x<100; x++)
    {
        Print("Loop number: " + x);
        TimeDelay(delay);
    }
}

i'd like to run the second instance without waiting until the first instance is finished.
function main()
{
     myLoop(2);
     myLoop(2);
}

so once the first myLoop started, i'd like the second myLoop to start immediately, they would be both running at the same time, my question is, what do you call this process?
is this process possible?(in java for example).
Thank you very much! :)

A: This typically requires some form of multithreading.
You would do something like:
function main
    start thread, calling myLoop(2)
    start thread, calling myLoop(2)

    ' Potentially wait for threads to complete
end function

For details on how this works in Java, see the Concurrency Tutorial.

A: Java implementation of your program will be similar to this.
    class MyThread implements Runnable{
       Thread t;
       int delay;
       MyThread (int delay) {
          t = new Thread(this,"My thread");
          this.delay = delay;
          t.start();
       }
       public void run() {
          for(int x=0; x<100; x++)
          {
           Print("Loop number: " + x);
           TimeDelay(delay);
          }
      }
    }
    class Demo {
       public static void main (String args[]){
         Thread t1 = new MyThread(2);
         Thread t2 = new MyThread(2);
         t1.join();
         t2.join();
       }
    }

A: The answer for your questions.

*

*What is this called?
A: Threading - running multiple tasks at a same time. (We call it as forking in PHP/Linux applications.)

*Is this possible in Java?
A: Offcourse this is possible. To be frank this is more easier to implement in Java. Please follow the above answers.

A: This is called an asynchronous computation. You can solve this cleanly with Futures. (You don't really need to do full-blown multithreading)
http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html


text:
Q: Can't access object properties even though I can see they exist I can't access any of the object properties, keep getting undefined.
I have tried
console.log(JSON.parse(this.$store.state.user.userId));

and
console.log(JSON.parse(this.$store.state.user[0].userId));

When I do
console.log(JSON.parse(this.$store.state.user.userId));

I get
"SyntaxError: Unexpected token u in JSON at position 0"

When I just do
 console.log(JSON.parse(this.$store.state.user));

I get the object and I can see the properties. It's just that whenever I try to access them I get undefined.

A:
When I just do console.log(JSON.parse(this.$store.state.user)); I get the object and I can see the properties.

This means that this.$store.state.user contains JSON string which describes the user object.
Thus JSON.parse(this.$store.state.user.userId) is incorrect. In this case you are trying to get property userId from string, getting undefined and JSON.parse function fails on the first symbol, which is 'u'.
You should use JSON.parse(this.$store.state.user).userId instead.


text:
Q: Dual boot linux/windows from UEFI A few month ago I've installed Linux as a second system. As a boot manager I use rEFInd.
Unfortunately, last windows update changed it somehow back to the Windows Boot Manager.
Now, my computer automatically boots to Windows. But I've figured out that I can boot to Linux through going in windows to setting > Update & security > restore > Advanced setup, then choosing Linux in other operating systems.
Is it somehow possible to always go to this menu when you startup a PC? Ive allready tried to reinstall reFIND and this solved the problem, but is it really possible to do this using UEFI? I know about bcdedit /set {globalsettings} advancedoptions command, but it does not give you a choice of operating system. And also I've disabled Secure Boot on my Motherboard settings (I have an MSI motherboard, and in boot mode options, Legacy+UEFI is selected)
Thanks for help!


text:
Q: Calling a function after another function is called I'm programming a controller for use with Ableton Live 8 using the Python-based API. In my code I use a method provided in the API to watch for changes in a property's value, and call a function whenever the value changes. My goal is to change the color of the clip when the value change is noticed.
I have my code completed, and it compiles without error. From Ableton's log:
742234 ms. RemoteScriptError: RuntimeError
742234 ms. RemoteScriptError: :
742234 ms. RemoteScriptError: Changes cannot be triggered by notifications
742234 ms. RemoteScriptError:

It appears this is the result of using the built-in notification system to make a change to the live set during notification. Triggering the actual change AFTER the listening function has finished executing should work. Is this possible using Python?
Edit for clarification:
currently we have

*

*value change noticed, function called

*function attempts to change the clips color (results in error)

we need

*

*listener notices value change, function called

*function finds the new color value

*function execution ends

*another function is called outside the listener's scope, and changes the clips color

A: I did a lot in M4L and know this error by heart :)
I'm afraid you can't do anything about that - to my noob eyes it looks like a built-in security mechanism so you can't loop (Something changed? Change it! Something changed...).
In M4L i used Javascript Tasks to separate the steps (Tasks forget nearly everything),
something like
Observer -> Something changed
Create a Task that reacts
task.execute() or task.schedule(time)
Maybe the python threading module can achieve something similar?
BTW, if you happen to understand anything about the _Framework-Tasks, let me know.

A: I was having the same issue trying to delete a track from a clip stop listener, then I found this thread and followed @user2323980 suggestion.
There seems to be a "_tasks" object on every Framework class (I found it throught log_message inside ClipSlotComponent and ControlSurface) that handles concurrency between tasks. And it's really simple to use it:
self._tasks.add(Task.run(func, args))
I found some uses of it on Push and MK2 scripts, those are good references.


text:
Q: Ruby on Rails: upload files with progress bar and checking of filesize before upload Are there any gems / plugins that allow for a slick implementation?
Bonus for allowing multiple uploads =)

A: The generic mechanism for uploading is to encode the entirety of the file to be uploaded within the HTTP request entity. Therefore, by the time the server-side application even sees the request, the file has already been uploaded (although some servers permit the optimization that the server-side processing can begin before the entirety of the HTTP request has been transmitted to the server, but will block if the application needs data from the HTTP request that has not yet been received).
There are several Flash-based uploaders that permit uploading files in separate HTTP requests; they require that the server application have a separate endpoint accepting HTTP requests particular to uploading files. Some even implement progress bars, multiple file uploads, client-side constraints on content-type and content-length, and more besides. At random: YUI Uploader, Uploadify, FancyUpload.

A: I used Uploadify which is written as a jQuery plugin, as the multi-file uploader for my blogging app called "Rehash" (source code), check the ProjectsController#new_upload action. We have used this on a few projects and keep improving our implementation. The tricky part with any Flash multi-file uploader (like Uploadify or FancyUpload) is dealing with Rails' cross-site request forgery protection and cookies. You want to ensure the request comes from the application and you may want to authenticate the upload. In Rehash I only allow the site administrator to upload for example, so I need to check both the session key and the authentication token. John Nunemaker has a nice blog post on Rails Tips on getting Uploadify set up, outlining the current best practice of dealing with the Flash/session stuff as Rack middleware, using Paperclip for file uploads, which is our same setup. In the end you have a nice multi-file uploader with style-able progress bars, but it is a good amount of work initially.
Uploadify has a sizeLimit option as well, check the docs.

A: I use the YUI uploader. Industrial strength, large community, book etc. I had to roll my own integration into Rails, but wasn't hard.
PS, check out the widget's examples, listed on the far right side of the page.


text:
Q: Why can't we try to prove the twin prime conjecture using a Turing machine? Suppose a Turing machine is fed all the basic axioms and it uses the mathematical inference to prove theorems then using these theorems it proves further theorems and so on. At every iteration it checks whether the "Newly" proven theorem is the twin prime conjecture (TPC) or not if yes, it terminates if not it goes on.
Please correct me if I am wrong .

A: I think you might have the idea from This video. The idea is mentioned at minute 24. However afterwards it is mentioned that there are problems that cannot be decided by a turing machine, for example the halting problem.
Since we know that the halting problem cannot be solved by a turing machine, we know that not every problem can be solved by a turing machine.
It may however be possible to prove the twin prime conjecture using this method, we just don't know.
If it where undecidable, it could not be proven by our current system of mathematics.


text:
Q: WebStorm + Webpack: autocompletion for global objects I have an utilities module in my project, which is available globally through webpack's ProvidePlugin under name "F". Code looks like this:
/** @typedef {Object} F */

/** @function F.somefunc */
export function somefunc() ...

I've added this module to libraries list, like here, so WebStorm does not complain about "missing import statement". And due to JSDoc, Ctrl + Click on F.somefunc(...) in code opens declaration of somefunc.
But there are still problems:

*

*Ctrl + Click on F itself still says "cannot find declaration to go to" – while I expect it to open a line with @typedef {Object} F

*autocompletion for F does not work even with all my JSDoc:

I tried to add /** @global */ directive to declaration of F, tried to add /** @memberOf F */ to each function, but it does nothing.
How to make these things work?
WebStorm version is 2017.2


text:
Q: calculate currents class ab amplifier

simulate this circuit – Schematic created using CircuitLab
I have been designing the same basic AB amplifier, trying to really understand all the intricacies of currents, voltages, and power flowing throughout the circuit. I have ignored all signal inputs for now as I am focusing on understanding the biasing with feedback in this circuit. The final circuit has capacitors, I have not included them for simplicity. I have built the circuit with appropriate caps, etc. The circuit works, but the transistors get very hot under quiescent conditions. (Have not yet included emitter resistors R1 and R2, which might explain the currents).
Modeling this circuit in spice, there is a 7.6mA total current supplied by V1.  The current flowing through the R3-D1-D2-R4 is 5.8mA and the current flowing through the collector of Q2 is 1.8mA.  This makes sense with KCL at node 1. The voltage at the base of Q2 is 6.2 volts.  Assuming 0.7 Vbe, the emitter voltage at Q2 will be 5.5 volts.  According to spice, the voltage at node 2 is 5.48 volts, or 20mV dropped across R1.  This won't work since 1.8mA is flowing through the Q2 collector (0.020/33 = 0.61mA), so am I missing how Q3 influences this?
Is something in the circuit causing a voltage drop across R3 of 5.8 V, or is something in the circuit causing 5.8 mA of current to flow through R3?  It kind of seems like a chicken v. egg. I don't know what is affecting what in the circuit.  Also, what is causing the 1.8mA through Q2?  If the voltage at the emitter of Q1 was known, the base voltage at Q1 could be known and also the voltage at node 2 due to the bias network.
What makes Q1's emitter voltage 0.5V as reported by Spice?  The collector voltage at Q1 is the same as the base voltage of Q3, which is two diode drops below the base of Q2.  But, I am then back to my first question.
It seems like there are a lot of unknowns, and if you can figure one of them out, the rest falls in place utilizing all the basic circuit analysis tools.  I have always struggled with where to start on a circuit like this though.
Finally, below is a picture of my Spice analysis.

Edit: I just simulated the same circuit without R1 and R2 and the currents do go way up (see below Spice analysis picture), which probably explains the heat.  I think my questions are still valid though.

A: Chicken & egg is an accurate way to describe what happens in this circuit... or any circuit that is enclosed in a feedback loop.
Here, you have the operating point - and therefore the output voltage at node 2 determined by the node 2 voltage fed back through bias resistor R6 to the input of your amplifier. This overall feedback is negative because there is only one inverting stage, Q1. Most circuit analysis is performed based on achieving a specified output.
So, to begin, assume output voltage (node2) = 1/2 V1 = 6 volts. This will allow the maximum peak-to-peak output voltage swing under signal conditions.
Choose a quiescent emitter current for Q2; let's say 10 milliamps.
Calculate the voltage drop across R1 = 0.33 volts.
Calculate voltage at the base of Q2 = 6.0 + 0.7 + 0.33 = 7.03 volts.
Calculate the voltage drop across R3 = 12 - 7.03 = 4.97 volts.
Calculate current through R3 = 4.97V/1000 = 4.97 milliamps.
Calculate collector voltage of Q1 = 7.03 - 0.7 - 0.7 = 5.63 volts.
Calculate the emitter voltage of Q3 = 5.63 + 0.7 = 6.33 volts.
Calculate the voltage drop across R2 = 6.33 - 6.0 = 0.33 volts.
Calculate the current through R2 = 0.33 volts / 33 ohms = 10 milliamps.
We now know that Q2 and Q3 emitter currents are ~ equal.
Assume Q1, Q2 & Q3 beta = 500.
Calculate Q2 & Q3 base currents = 10 milliamps / 500 = 20 microamps.
Calculate Q1 collector current = 4.97 milliamps - 0.02 milliamps - 0.02 milliamps = 4.93 milliamps.
Calculate Q1 base current = 4.93 / 500 = 10 microamps.
Calculate Q1 emitter current = 4.93 milliamps + 0.01 milliamps = 4.94 milliamps.
Calculate voltage across R4 = 100 * 4.94 milliamps = 0.494 volts.
Calculate Q1 base voltage = 0.7 + 0.494 = 1.194 volts.
Calculate current through R5 = 1.194 volts / 1500 ohms = 0.796 milliamps.
Calculate current through R6 = (6 volts - 1.194 volts) / 5000 ohms = 961 microamps.
Now you could reiterate, knowing that about a milliamp of the 10 milliamp emitter current of Q2 is flowing out of "Node 2" back to the base of Q1. Q2 & Q3 are dissipating about 60 milliwatts each, which might be closer to Class AB+, but you can see that lowering the quiescent power dissipation in the output transistors is as simple as choosing a lower value for quiescent emitter current in Q2 and Q3.
In practice, the operating point is often set by a resistor in parallel with diodes D1 & D2.
Hope this helps. Have fun!

A: The way to solve a circuit with feedback via first-order hand calculations is to:

*

*break the feedback loop

*Assume the current at that point is negligible

*use the broken node as your input

*write the circuit equations based on that unknown input

*Equate input and output

*Solve for that unknown

*Verify your assumptions

Breaking the circuit at node 2 and assuming all diodes and transistor junctions at 0.6V (this will cause problems for the current through Q2 and Q3, but we can take care of that later):

*

*Calculate the current through the base of Q1 as a function of Vnode2

*Calculate the current through D1 and D2 as a function of Vnode2

*Calculate the voltage in the middle of D1 and D2 as a function of Vnode2

*As D1, D2, Q2. Q3, R1, & R2 have symmetry. Vnode2 will be equal to the voltage between D1 & D2.

*Now solve for the one unknown

This gives you a first approximation. Now you can find the actual current and verify how much it deviates from the initial assumption. Note that you could have incorporated this unknown current in the above procedure and you would have ended up with two equations with two unknowns.
As an aside, calculating the actual current through Q2, Q3 is tricky as it requires using the actual non-linear equations for Vbe. This results in transcendental equations.


text:
Q: How to handle deeplink by URI in Navigation graph Android? How to open a deeplink using a CTA Uri in navigation components without losing backstack?
Motivation:
private fun openDeepLink(cta: String) { // cta= schema://host
  navigationController?.run{
    val deeplink = this
            .createDeepLink()
            .setDestination(cta)
            .build()

    handleDeepLink(deeplink)
   }
}

or
 navigationController?.createDeepLink()
            ?.setUriDestination(cta)
            ?.createTaskStackBuilder()
            ?.startActivities()

Using
navigationController?.handleDeepLink(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
just works with Up button (toolbar) and not with the system back button. I still can't understand why toolbar and native back are not aligned when I use:
toolbar.setupWithNavController(findNavController(R.id.activity_base_container))
and documentation says:

*

*@param toolbar The Toolbar that should be kept in sync with changes
  to the NavController.

With this I understand that toolbar will assume any changes of navController (changes on startDestination, open deeplinks etc)


text:
Q: What is the limiting ratio in differential equations? I have a homework question in ODE and don't see limiting ratio mentioned anywhere in the notes.  The question gives a two equation linear system solved by finding the eigenvalues and eigenvectors. It plots a few trajectories along with the eigenvectors and say to find the limiting ratio $\frac{y(t)}{x(t)}$.
Specifically it asks:
You have enough information to be able to predict the limiting ratio $\frac{y(t)}{x(t)}$ as $t$ gets large for any trajectory that does not start on the line through ${(0,0)}$ determined by the sucking eigenvector.
Here are the equations:
$x'(t) = -0.26 x(t) + 0.9 y(t) $
$y'(t) = 0.07 x(t) + 0.06 y(t)$

A: So I figured it out:
If you want to find the limiting ratio of a 2 linear equation diffeq, you need to take the slope of the eigenvector corresponding to a positive eigenvalue.  By slope I mean, if your eigenvector is {1.5, 3}, then you would plot a line that goes through {1.5, 3} and its opposite {-1.5, -3} and find the slope from there.


text:
Q: Concatenate Multidimensional Numpy array with 1D numpy array I have two numpy arrays (letters from the EMNIST dataset):
import scipy .io
emnist = scipy.io.loadmat(DATA_DIR + '/emnist-letters.mat')
data = emnist ['dataset']
X_train = data ['train'][0, 0]['images'][0, 0]
y_train = data ['train'][0, 0]['labels'][0, 0]

With the following dimensions:
X_train.shape = (124800, 784)
y_train.shape = (124800, 1)
Now, I want to concatenate the two, so that the new shape would be: (124800, 785).
Based on this link, I tried:
np.concatenate((X_train.shape, y_train.shape), axis = 0)

However, that results in the following shape: array([124800,    784, 124800,      1]).
How can I 'paste' y_train behind X_train so that the shape will be (124800, 785)?

A: If you concatenate two arrays, you have to concatenate the data inside the arrays, not the shape. Furthermore you want to concatenate on the second ("short") axis, which is axis=1:
np.concatenate((X_train, y_train), axis=1)


text:
Q: Make sure all threads exited In a win form application, I have an array of threads which are started like this:
bool stop = false;
Thread[] threads = new Thread[10];

for (int i = 0; i < threads.Length; i++)
    threads[i] = new Thread(new ThreadStart(Job));

// How to make sure all threads have exited, when the boolean = false

void Job()
{
    while (!stop)
        // Do something
}

Now if user press STOP, the boolean value for stop will set to true, so threads exit the Job method one after another. How can I make sure all threads are exited?
NOTE: I need traditional threading for my case and TaskLibrary doesn't fit my scenario.

A: Use the Join method to check if all threads have stopped.
 foreach (var t in threads)
 {
     t.Join();
 }

A: Have you thought about using BackgroundWorkers instead?  You said "traditional threads"..I'm not exactly sure what you mean so I don't know if this is a valid proposal or not, but here it is anyways in case Join() doesn't solve your problem
BackgroundWorker[] workers = new BackgroundWorker[10];
bool allThreadsDone = false;

// initialize BackgroundWorkers
for (int i = 0; i < 10; i++)
{
        workers[i] = new BackgroundWorker();
        workers[i].WorkerSupportsCancellation = true;
        workers[i].RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        workers[i].DoWork += new DoWorkEventHandler(AlgorithmsUI_DoWork);
        workers[i].RunWorkerAsync();
}

// thread entry point..DoWork is fired when RunWorkerAsync is called
void AlgorithmsUI_DoWork(object sender, DoWorkEventArgs e)
{
      while (!stop)
            // do something
}

// this event is fired when the BGW finishes execution
private void  worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    bool threadsStillRunning = false;
    foreach (BackgroundWorker worker in workers)
    {
        if (worker.IsBusy)
        {
            threadsStillRunning = true;
            break;
        }
    }
    if (!threadsStillRunning)
        allThreadsDone = true;
}

protected override OnFormClosing(FormClosingEventArgs e)
{
         if (!allThreadsDone)
         {
              e.Cancel = true;
              MessageaBox.Show("Threads still running!");
         }
}

This should prevent your form from closing if any threads are still running.

A: I'm not sure if this is what you're looking for, but here's a simple solution I used back in .NET 3.0 to make sure a large but deterministic number of threads had completed before continuing:
Global:
AutoResetEvent threadPoolComplete = new AutoResetEvent(false);
static int numThreadsToRun;

As you activate the threads:
numThreadsToRun = [number of threads];
[start your threads];
threadPoolComplete.WaitOne();

At the end of each thread's code:
if (Interlocked.Decrement(ref numThreadsToRun) == 0)
{
   threadPoolComplete.Set();
}


text:
Q: Ublaboo/Datagrid - InlineAdd row is hidden after update to Ublaboo/Datagrid v6.2, PHP 7.3 and Nette 3.0, in all pages (grids) where I used inlineAdd feature, this feature stopped working. I figured out, that after click on Add button, row with inlineAdd is added into table but with class datagrid-row-inline-add-hidden, which is making this row hidden.
I tried to download Ublaboo/Datagrid Playground project from GIT and paste my code there. I also tried to install there my bower.json to be sure, that I have the same CSS and JS. But in the playground project that I edited is everything working fine with same code as I have in my project.
Can anyone give me some advice where to look for bugs, please?
Thank you.


text:
Q: 12v 16 amps to 12v 3 amps? I got a old desktop SMPS rated 250watts. In the output panel its written as, it can supply  a output of 12v16amp. So my question is, it is possible to supply a steady 12v3amps from a 12v16amp smps. I also checked connecting my motor with the smps but the motor rotated for just 2 seconds and turned off automatically.
Thanks!

A: It is indeed possible to supply a steady 12 V at 3 amps from a 12 V 16 amp SMPS.
The thing to watch out for with ye olde PC PSUs is that some of them need some load on other rails to be stable.
I thought, and could well be wrong, that it was the case that a load (e.g. some 12 V fan that is to hand) was required on the 12 V rail for the PSU to stay on, but it could be that you need a small load on the 5 V and/or 3.3 V rails.
Drawing a few hundred milliamps from the other rails at the same time should enable the PSU to stay on.

A: This sounds like a problem with the motor itself.  Or, maybe the power supply is malfunctioning.
Merely having a power supply that is capable of providing more current than is required isn't a problem because the load will determine how much power it draws.
So the answer to your title question is that you can reduce 12V16A to 12V3A by making sure your load doesn't try to draw more than 3A.
Time to break out the multimeter and watch the voltage into the motor and see what is happening.  Or try a different motor to try to localize the problem.
If it looks like the problem is the power supply, then you can confirm by using a lab-style bench power supply to run the motor.


text:
Q: Как импортировать функцию из другой папки Мой проект имеет следующую структуру:
Project1
        dev
           test.py
        main.py

В файле test.py есть функция get_summa(), которую мне надо импортировать в файл main.py.
Подскажите, пожалуйста, как правильно импортировать нужную функцию из другой папки

A: Попробуйте так:
from dev.test import get_summa


text:
Q: how to get list for upcoming birthdays of all facebook friends I have made a program in which i am getting list of all facebook friends as their birthday comes like in form of January to December, so here i am getting birthdays of all my facebook friends those are past away also, and now i just want to show list of all upcoming birthdays.
MyLocalDB.java
public class MyLocalDB {
private static final String DATABASE_NAME = "bdrem";
private static final String TABLE_FRIEND = "friend";
private static final String TABLE_FRIEND_TEMP = "friend_temp";
private static final String TABLE_SETTINGS = "settings";
private static final int DATABASE_VERSION = 4;

public static final String KEY_ID = "friendID";
public static final int ID_COLUMN = 0;
// The name and column index of each column in friend's table
public static final String KEY_FBID = "facebookID";
public static final int FBID_COLUMN = 1;
public static final String KEY_NAME = "name";
public static final int NAME_COLUMN = 2;
public static final String KEY_BIRTHDAY = "birthday";
public static final int BIRTHDAY_COLUMN = 3;
public static final String KEY_PIC = "picture";
public static final int PIC_COLUMN = 4;
public static final String KEY_BDAYMESSAGE = "message";
public static final int BDAYMESSAGE_COLUMN = 5;
public static final String KEY_AUTOPOST = "autopost";
public static final int AUTOPOST_COLUMN = 6;

// The name and column index of each column in setting's table
public static final String KEY_SETTINGS_ID = "settingsId";
public static final String KEY_SETTINGS_VALUE = "settingsValue";
public static final int SETTINGS_KEY_COLUMN = 0;
public static final int SETTINGS_VALUE_COLUMN = 1;

private static final String SETTINGS_CREATE = "create table "
        + TABLE_SETTINGS + " ( " + KEY_SETTINGS_ID + " varchar(255), "
        + KEY_SETTINGS_VALUE + " varchar(255)" + " );";

private static final String FRIENDS_CREATE = "create table " + TABLE_FRIEND
        + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_FBID
        + " int, " + KEY_NAME + " varchar(50)," + KEY_BIRTHDAY
        + " varchar(25), " + KEY_PIC + " varchar(255)," + KEY_BDAYMESSAGE
        + " varchar(255), " + KEY_AUTOPOST + " varchar(10)" + " );";

private static final String FRIENDS_TEMP_CREATE = "create table "
        + TABLE_FRIEND_TEMP + " (" + KEY_ID
        + " integer primary key autoincrement, " + KEY_FBID + " int, "
        + KEY_NAME + " varchar(50)," + KEY_BIRTHDAY + " varchar(25), "
        + KEY_PIC + " varchar(255)," + KEY_BDAYMESSAGE + " varchar(255), "
        + KEY_AUTOPOST + " varchar(10)" + " );";

private SQLiteDatabase localDB;
// private final Context context;
private LocalDBHelper dbHelper;

public MyLocalDB(Context context) {
    // this.context = context;
    this.dbHelper = new LocalDBHelper(context, DATABASE_NAME, null,
            DATABASE_VERSION);
}

public void open() throws SQLException {
    localDB = dbHelper.getWritableDatabase();
}

private static class LocalDBHelper extends SQLiteOpenHelper {

    public LocalDBHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "DB create");
        db.execSQL(FRIENDS_CREATE);
        db.execSQL(SETTINGS_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d(TAG, "Upgrading from " + oldVersion + " to " + newVersion
                + ", which may destroy all the old data.");

        // Drop the old table
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FRIEND);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_FRIEND_TEMP);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS);

        // Create a new one
        onCreate(db);
    }
}

// Local storage should have one table for key-value pair
public String getSettings(String settingsKey) {
    String settingsValue = "";
    try {
        Cursor settings = localDB.query(true, TABLE_SETTINGS, null,
                KEY_SETTINGS_ID + " = ?", new String[] { settingsKey },
                null, null, null, null);
        if ((settings.getCount() == 0) || !settings.moveToNext()) {
            return "";
        }
        settingsValue = settings.getString(SETTINGS_VALUE_COLUMN);
    } catch (SQLiteException ex) {
        Log.d(TAG, ex.getMessage());
    }
    Log.v(TAG, "setting: " + settingsValue);
    return settingsValue;
}

public void setSettings(String key, String value) {
    Log.d(TAG, key + ", " + value);
    try {
        localDB.execSQL("delete from " + TABLE_SETTINGS + " where "
                + KEY_SETTINGS_ID + " = '" + key + "';");
        localDB.execSQL("insert into " + TABLE_SETTINGS + " values ('"
                + key + "', '" + value + "');");
    } catch (SQLiteException ex) {
        Log.d(TAG, ex.getMessage());
    }
}

public List<MyFriend> getAllFriends() {

    return getFriendsFilteredBy(null);
}

public MyFriend getFriendByFbID(String facebookId) {

    Cursor friendResults = localDB.query(false, TABLE_FRIEND, null,
            KEY_FBID + "=" + facebookId, null, null, null, null, null);

    if ((friendResults.getCount() == 0) || !friendResults.moveToNext()) {  //First
        return null;
    }

    MyFriend friend = new MyFriend();
    friend.setBdayMessage(friendResults.getString(BDAYMESSAGE_COLUMN));
    friend.setAutoPost(Boolean.valueOf(friendResults
            .getString(AUTOPOST_COLUMN)));
    return friend;
}

public List<MyFriend> getFriendsFilteredBy(Filter filterBy) {
    List<MyFriend> friends = new ArrayList<MyFriend>();
    String[] resultColumns = new String[] { KEY_ID, KEY_FBID, KEY_NAME,
            KEY_BIRTHDAY, KEY_PIC, KEY_BDAYMESSAGE, KEY_AUTOPOST };

    String selection = null;
    String[] selectionArgs = null;
    String orderBy = KEY_BIRTHDAY;

    if (filterBy != null) {
        switch (filterBy) {
        case MONTH:
            selection = KEY_BIRTHDAY + " LIKE ?";
            selectionArgs = new String[1];
            selectionArgs[0] = MyUtils.getCurrentMonth() + "%";
            orderBy = KEY_BIRTHDAY;
            Log.v(TAG, "localdb.month- " + selectionArgs[0]);
            break;
        case WEEK:
            selection = KEY_BIRTHDAY + " >= ? and " + KEY_BIRTHDAY
                    + " <= ?";
            selectionArgs = new String[2];
            selectionArgs[0] = MyUtils.getCurrentMonth() + "/"
                    + MyUtils.getCurrentWeekDays()[0];
            selectionArgs[1] = MyUtils.getCurrentMonth() + "/"
                    + MyUtils.getCurrentWeekDays()[1];
            orderBy = KEY_BIRTHDAY;
            Log.v(TAG, "localdb.week- " + selectionArgs[0] + ","
                    + selectionArgs[1]);
            break;
        case DAY:
            selection = KEY_BIRTHDAY + " LIKE ?";
            selectionArgs = new String[1];
            selectionArgs[0] = MyUtils.getCurrentMonth() + "/"
                    + MyUtils.getCurrentWeekDays()[0] + "%";
            selectionArgs[0] = "12/23%";
            Log.v(TAG, "localdb.day- " + selectionArgs[0]);
            break;
        default:
            break;
        }
    }
    /*
     * TESTING else{ selection = "name LIKE ?"; selectionArgs = new
     * String[1]; selectionArgs[0] = "%aad%"; }
     */

    Cursor allRows = localDB.query(false, TABLE_FRIEND, resultColumns,
            selection, selectionArgs, null, null, orderBy, null);

    if (allRows.moveToNext()) {
        do {
            String fbId = allRows.getString(FBID_COLUMN);
            String name = allRows.getString(NAME_COLUMN);
            String birthday = allRows.getString(BIRTHDAY_COLUMN);
            String picture = allRows.getString(PIC_COLUMN);
            String message = allRows.getString(BDAYMESSAGE_COLUMN);
            boolean isAutoPost = allRows.getString(AUTOPOST_COLUMN).equals(
                    "false") ? false : true;
            MyFriend friend = new MyFriend(fbId, name, birthday, picture,
                    message, isAutoPost);
            friends.add(friend);
        } while (allRows.moveToNext()); //Next
    }
    return friends;
}

public Report syncFriends(List<MyFriend> friends) {
    Log.v(TAG, "mylocaldb.syncfriends Sync started!" + friends.size());
    localDB.execSQL("DROP TABLE IF EXISTS " + TABLE_FRIEND_TEMP);
    localDB.execSQL(FRIENDS_TEMP_CREATE);

    for (MyFriend friend : friends) {
        insertFriend(friend, TABLE_FRIEND_TEMP);
    }

    localDB.execSQL("update " + TABLE_FRIEND_TEMP
            + " set message = (select message from " + TABLE_FRIEND
            + " where " + TABLE_FRIEND + ".facebookID = "
            + TABLE_FRIEND_TEMP + ".facebookID)");

    localDB.execSQL("update " + TABLE_FRIEND_TEMP
            + " set message = ' ' where message is null;");

    localDB.execSQL("update " + TABLE_FRIEND_TEMP
            + " set autopost = (select autopost from " + TABLE_FRIEND
            + " where " + TABLE_FRIEND + ".facebookID = "
            + TABLE_FRIEND_TEMP + ".facebookID)");

    localDB.execSQL("update " + TABLE_FRIEND_TEMP
            + " set autopost = 'false' where autopost is null;");

    localDB.execSQL("DROP TABLE IF EXISTS " + TABLE_FRIEND);
    localDB.execSQL("ALTER TABLE " + TABLE_FRIEND_TEMP + " RENAME to "
            + TABLE_FRIEND);

    friends.clear();
    friends = getAllFriends();

    Log.v(TAG, "mylocaldb.syncfriends Sync finished." + friends.size());
    return new Report(true, "Friends Synced");
}

public Report storeFriends(List<MyFriend> friends) {
    int count = 0;
    for (MyFriend friend : friends) {
        if (storeFriend(friend).isSuccess == true) {
            count++;
        }
    }

    if (count == friends.size()) {
        return new Report(true, count + " friends stored.");
    } else {
        return new Report(false, "Only " + count + " friends stored.");
    }
}

public Report storeFriend(MyFriend friend) {
    Cursor friendResults = localDB.query(false, TABLE_FRIEND, new String[] {
            KEY_ID, KEY_FBID }, KEY_FBID + "=" + friend.getFbID(), null,
            null, null, null, null);
    Report report = null;
    // If friend doesn't exist, insert it
    if ((friendResults.getCount() == 0) || !friendResults.moveToNext()) {
        report = insertFriend(friend);
        return report;
    }
    // If friend exists, update it
    else {
        long rowId = friendResults.getLong(ID_COLUMN);
        String message = friend.getBdayMessage();
        boolean isAutoPost = friend.isAutoPost();
        report = saveMessage(rowId, message, isAutoPost);
        report = updateFriend(rowId, friend);
        return report;
    }
}

// Insert friend in database

public Report insertFriend(MyFriend friend) {
    return insertFriend(friend, TABLE_FRIEND);
}

public Report insertFriend(MyFriend friend, String tableName) {
    ContentValues newFriend = new ContentValues();
    newFriend.put(KEY_FBID, friend.getFbID());
    newFriend.put(KEY_NAME, friend.getName());
    newFriend.put(KEY_BIRTHDAY, friend.getBday());
    newFriend.put(KEY_PIC, friend.getPic());
    newFriend.put(KEY_BDAYMESSAGE, friend.getBdayMessage());
    boolean isAutoPost = friend.isAutoPost();
    if (isAutoPost) {
        newFriend.put(KEY_AUTOPOST, "true");
    } else
        newFriend.put(KEY_AUTOPOST, "false");

    try {
        localDB.insert(tableName, null, newFriend);
    } catch (SQLiteException ex) {
        return new Report(false, ex.getMessage());
    }

    return new Report(true, "Friend inserted successfully!");
}

// Update friend in database
public Report updateFriend(long rowId, MyFriend friend) {

    ContentValues updatedFriend = new ContentValues();

    updatedFriend.put(KEY_FBID, friend.getFbID());
    updatedFriend.put(KEY_NAME, friend.getName());
    updatedFriend.put(KEY_BIRTHDAY, friend.getBday());
    updatedFriend.put(KEY_PIC, friend.getPic());
    updatedFriend.put(KEY_BDAYMESSAGE, friend.getBdayMessage());
    boolean isAutoPost = friend.isAutoPost();
    if (isAutoPost) {
        updatedFriend.put(KEY_AUTOPOST, "true");
    } else
        updatedFriend.put(KEY_AUTOPOST, "false");

    try {
        String where = KEY_ID + "=" + rowId;
        localDB.update(TABLE_FRIEND, updatedFriend, where, null);
    } catch (SQLiteException ex) {
        return new Report(false, ex.getMessage());
    }
    return new Report(true, "Friend is updated successfully!");
}

public Report saveMessage(long rowId, String message, boolean isAutoPost) {

    ContentValues updatedFriend = new ContentValues();
    updatedFriend.put(KEY_BDAYMESSAGE, message);

    if (isAutoPost) {
        updatedFriend.put(KEY_AUTOPOST, "true");
    } else
        updatedFriend.put(KEY_AUTOPOST, "false");

    try {
        String where = KEY_ID + "=" + rowId;
        localDB.update(TABLE_FRIEND, updatedFriend, where, null);
    } catch (SQLiteException ex) {
        return new Report(false, ex.getMessage());
    }
    return new Report(true, "Friend is updated successfully!");
}

public Report saveMessageByFbID(String ID, String message,
        boolean isAutoPost) {

    ContentValues updatedFriend = new ContentValues();
    updatedFriend.put(KEY_BDAYMESSAGE, message);
    updatedFriend.put(KEY_AUTOPOST, isAutoPost ? "true" : "false");

    try {
        String where = KEY_FBID + " = ?";
        localDB.update(TABLE_FRIEND, updatedFriend, where,
                new String[] { ID });
    } catch (SQLiteException ex) {
        return new Report(false, ex.getMessage());
    }
    return new Report(true, "Friend is updated successfully!");
}

public Report removeFriend(long rowId) {

    String where = KEY_ID + "=" + rowId;
    try {
        localDB.delete(TABLE_FRIEND, where, null);
    } catch (SQLiteException ex) {
        return new Report(false, ex.getMessage());
    }
    return new Report(false, "Friend is removed successfully!");
}

public void close() {
    localDB.close();
}
   }

A: There is nothing hard here. Using Graph API:

*

*Get your users birth dates: /YOUR_ID?fields=friends.fields(birthday).

*Sort the dates by using everyone's day and month of birth.

*Get the current date and display the following birth dates.


text:
Q: Конфиг docker-compose в зависимости от переменных окружения Есть приложение в docker, в нём есть контейнер nginx, который его и отдаёт.
Приложение не знает об окружении в котором будет использоваться. Возможно, ему нужно пробросить свой порт на хост, чтобы им можно было пользоваться. Или же им будут пользоваться из другого контейнера и можно обойтись без задействования хост-порта.
Хочется в docker-compose.yml иметь возможность:

*

*Указывать порт в .env. Здесь всё просто: ports: ${EXTERNAL_PORT}:80

*Либо не указать вообще - тогда порт и не должен прокидываться. Список ports должен быть пустым.

Можно ли как-то это реализовать?

A: Единственное, что придумал, это использовать docker-compose.override.yml.

*

*В основном docker-compose.yml не указываем вообще порт

*docker-compose.override.yml добавляем в игнор в репе

*В том окружении, где нужно создаём его и прописываем что-то вроде:

version: "3.8"

services:

    www:
        ports:
            - "${HOST_PORT}:80"

UPDATE
Второе решение - генерировать docker-composer.yml. У меня была идея сделать для этого простой шаблонизатор на PHP (так как проект на нём), в комментариях предлагают Makefile.
Проблема в том, что, раз мы используем Docker, то хотелось бы максимально разгрузить хост. Здесь же нам на хосте нужны языки/библиотеки для генерации конфига.
Так что второе решение (на любителя) - создать ещё один docker-compose-проект, предназначенный для генерации конфига для основного проекта :)

A: В docker-compose.yml нет поддержки условий, поэтому вариант с docker-compose.override.yml, который вы сами
предложили - практически единственный способ добавления гибкости.
Другой вариант - использовать несколько yml-файлов. При запуске docker-compose можно указать несколько yml-файлов,
они будут слиты в единую конфигурацию: docker-compose -f файл1.yml -f файл2.yml ... up ...
Кастомная конфигурация через Makefile
Нужно написать Makefile, который будет создавать кастомную конфигурацию. Таким способом можно реализовать любую логику.
Выглядит это следующим образом:

*

*есть файл конфигурации .env, который влияет на конфигурацию

*вы делаете make up, и утилита make запускает цель up из файла Makefile, в котором собирается собственный
кастомный вариант docker-compose-dev.yml
Ниже - пример, в котором проверяется .env файл на наличие HOST_PORT и опционально добавляется порт.
Сначала устанавливаем утилиту yq, которая может сливать yaml-файлы:
sudo add-apt-repository ppa:rmescandon/yq
sudo apt-get install yq

Makefile:
####################################
# Список сервисов для запуска
####################################

SERVICES=www mysql nginx

# Запуск всех контейнеров
.PHONY: up
up: docker-compose-dev.yml

# для запуска с кастомной конфигурацией нужно раскомментировать следующую строку, она должна начинаться с Tab
# @docker-compose -f docker-compose-dev.yml up -d ${SERVICES}

# для примера тут запускается diff, который покажет разницу между 2 файлами
    @diff docker-compose.yml docker-compose-dev.yml || true

# файл-цель зависит от других файлов и будет пересобираться при их изменении
docker-compose-dev.yml: docker-compose.yml with-port.yml .env
    @/usr/bin/bash build-yml.sh

build-yml.sh:
#!/usr/bin/bash

grep -qP '^HOST_PORT=' .env

[ $? -eq 0 ] && \
    yq merge docker-compose.yml with-port.yml > docker-compose-dev.yml || \
    cp docker-compose.yml docker-compose-dev.yml

with-port.yml:
services:
  www:
    ports:
      - "${HOST_PORT}:80"

.env:
# Порт приложения
HOST_PORT=8080

Проверка: запускаем make up, diff выдает такую разницу:
>     ports:
>       - "${HOST_PORT}:80"

Если удалить HOST_PORT, порт из yml-файла исчезает.
Я использовал связку bash + yq, но в более сложных кейсах лучше написать скрипт на более функциональном языке.
На enSO есть аналогичный вопрос.


text:
Q: 'ForwardManyToOneDescriptor' object has no attribute 'all Now, i have problem w M2O relectionship :(
Model.py
 class StorageDoc(models.Model):  # tabela dokumentująca ruch na magazynie
        typeList = (
            (' ', " "),
            ('WZ', "WZ"),
            ('PZ', "PZ"),
            ('PM', "PM")
        )
        docType = models.CharField(max_length=10, choices=typeList, default=' ')
        storageName = models.ForeignKey(DictStorage, on_delete=models.DO_NOTHING)
        createTime = models.DateTimeField(auto_now=True)
        orderNumber = models.CharField(max_length=64, blank=True)

class StorageDocPosition(models.Model):
                    storageDoc = models.ForeignKey(StorageDoc, on_delete=models.DO_NOTHING, related_name="sds")
                    item = models.ForeignKey(Part, on_delete=models.DO_NOTHING)
                    volumeUsed = models.IntegerField()
                    volumeBefore = models.IntegerField()
                    volumeAfter = models.IntegerField()

views.py
def StorageDocList (request):
    s_documents = StorageDocPosition.objects.all().prefetch_related("storageDoc")
    for s_document in s_documents:
        s_documentP = StorageDocPosition.storageDoc.all()

    return render(request, 'StorageDocList.html', {'storageDocAll': s_documents})

my error is:

    'ForwardManyToOneDescriptor' object has no attribute 'all'

why I can not use "all" in this case?
How fix it?
Thanks for help :

A: First of all, I don't quiet understant what you're trying to do with this for loop:
for s_document in s_documents:
    s_documentP = StorageDocPosition.storageDoc.all()

Besides the typo in s_document, you won't change the variable, you're just modifying a temporary iterator, the original s_document will still be the same, and you'd me passing in the context the same as the first line in the SotrageDocList function.
If what you're trying to achieve is getting all the prefetch related documents, just eliminate the for loop and pass a queryset into the context.
Hope this helped!


text:
Q: Calculate $\lim_{n\to\infty}\int_0^\frac{1}{n} \frac{e^{-t} \sin{\frac{t}{n}} dt}{(1+\frac{t}{n}^2)\arctan{\frac{t}{n}}}$ How to find

$$\lim_{n\to\infty}\int_0^\frac{1}{n} \frac{e^{-t} \sin{\frac{t}{n}} dt}{(1+\frac{t}{n}^2)\arctan{\frac{t}{n}}}?$$

Any help is welcome.
Thanks in advance.

A: Notice that the function $g(x)=\left|\frac{\sin x}{\arctan x}\right|$ is bounded by some $C$ on the interval $[0,1]$, so
$$\left|\frac{e^{-t}\sin\frac{t}{n}}{\left(1+\frac{t^2}n\right)\arctan \frac{t}{n}}\right| \le C$$
Therefore,
$$\left|\int_0^{1/n}\frac{e^{-t}\sin\frac{t}{n}}{\left(1+\frac{t^2}n\right)\arctan \frac{t}{n}}\ dt\right| \le \frac{C}{n}.$$
This means that the desired limit is $0$.
Comment:  When you change the upper bound of the integral from $1/n$ to $n$, the problem becomes more interesting.

A: Let $f_n= \frac{e^{-t} \sin{\frac{t}{n}} dt}{(1+\frac{t}{n}^2)\arctan{\frac{t}{n}}}1_{[0,\frac{1}{n}]}$.
We have that $f_n(t) \to 0$ since $g(tx)=\frac{\sin{tx}}{\arctan{tx}} \to t^2$  as $x \to 0$ thus $0 \leq |g(\frac{t}{n})| \leq  (1+\frac{1}{n^2}) \leq 2$ for all $t \in (0,\delta_n]$ for some $\frac{1}{2}>\delta_n >0$
We can choose $\delta_n$ such that $\delta _1>\delta_2>...>\delta_n>...$
Thus $(0,\delta_n] \subseteq (0,\delta_1],\forall n \in \Bbb{N}$ so $|g(\frac{t}{n})| \leq 2 ,\forall n \in \Bbb{N}$
Also $|g(\frac{t}{n})|e^{-t} \leq M e^{-t}, \forall x \in [\delta_0,+\infty]$ for some $M>0$ independent of $n$
Thus  $|f_n(t)| \leq 2e^{-t}+Me^{-t} \in L^1[0,+\infty]$ because $1_{[\delta_0,+\infty]},1_{(0,\delta_0]} \leq 1$
So by dominated convergence ,the limit is zero.


text:
Q: Image loading inconsistent with Jekyll + GitHub Pages I've recently created a Jekyll/Github pages site in the hopes of starting a small blog to share thoughts and side projects. After writing my first post, I've realized that some but not all of my images within the post are not working. I have been trying for hours to figure out why in vain. Below is my assets/images folder. Images suffixed with 3, 4, and 5 display correctly, but images 1 and 2 do not. Is it possible that Jekyll/Github only takes images of a certain size threshold?

I believe my _config.yml is configured appropriately. It is at least able to find images 3-5.
url : "https://selfawarelemon.github.io/evil-lemonade"

For reference, here is how I am referring to all the images within the blog post. Again, this logic works for images 3-5 but not images 1-2.

The only difference in each tag is the width I supply to make the images appropriately sized with the width argument. I'm not sure what the issue is here. I've additionally tried waiting a while after a commit to see if it simply takes time to load the images but that didn't work. Is there something super obvious I am missing or simply a property of Jekyll/Github pages I am ignorant to?

A: As you can see in the image provided, the filenames are capitalized:
101820_1.PNG
101820_2.PNG
101820_3.PNG
// ...

However, in your image tag, the filename is not capitalized:

Capitalizing the filname should fix the issue:

Paths in URLs are case-sensitive according to the standard. Depending on the operating system Github Pages is running on, case sensitive image paths may or may not matter. This is probably what is causing the inconsistency in rendering the images.
This answer was suggested by @shubhamjha in a comment. I created this small answer for future visitors with the same problem

A: The quick solution is to keep the case of asset extension (uppercase/lowercase) as it is e.g. https://whoami-shubham.github.io/assets/img/earth.jpg and https://whoami-shubham.github.io/assets/img/earth.JPG would give a different result.  In your image path extension of the image is png in lowercase however in actual it is PNG uppercase. so changing it to uppercase would solve the issue.

Domain names are case insensitive according to RFC 4343.
The rest of the URL may or may not be case sensitive.
for e.g.

*

*https://stackoverflow.com/Tags

*https://stackoverflow.com/tags
above two URLs give the same result it seems StackOverflow URLs are not case sensitive, However, the following GitHub page URLs are case sensitive.

*

*https://whoami-shubham.github.io/hello-world

*https://whoami-shubham.github.io/Hello-world


text:
Q: Can one make a sized list using singleton Nats (like 0, 1, ...) from Lists in Haskell? While learning about singletons and (semi) dependent typing, I started trying to make a sized list from a normal Haskell list with sizes given by Nats such as 0, 1, 2, 3,... instead of Z, S Z, S (S Z), etc.. I'm using the Data.Singletons.TypeLits library btw. (singletons-2.5.1).
This is the way I've been trying to do it:
data NatList (a :: *) (n :: Nat) where
    Nah :: NatList a 0
    Yea :: a -> NatList a n -> NatList a (n + 1)

fromList :: SNat n -> [a] -> NatList a n
fromList s []     = Nah
fromList s (x:xs) = Yea x (fromList (s %- (SNat :: SNat 1)) xs)

This code doesn't compile and gives me an error
"Couldn't match type 'n' with '0'
      'n' is a rigid type variable bound by
        the type signature for:
          fromList :: forall (n :: Nat) a. SNat n -> [a] -> NatList a n

A: After some time away from the problem I came back and found a solution that works for me: use an existential wrapper for the sized list type and convert the runtime list
to that.
data SizedList (a :: *) (n :: Nat) where
    Nil  :: SizedList a 0
    Cons :: a -> SizedList a n -> SizedList a (n+1)

data SomeSL (a :: *) where
    MkSomeSL :: KnownNat n => SNat n -> SizedList a n -> SomeSL a

toList :: SizedList a n -> [a]
toList Nil         = []
toList (Cons x xs) = x : toList xs

fromList :: [a] -> SomeSL a
fromList []     = MkSomeSL (SNat @0) Nil
fromList (x:xs) = case (fromList xs) of
    MkSomeSL n ys -> MkSomeSL (n %+ SNat @1) (Cons x ys)

toList_ :: SomeSL a -> [a]
toList_ (MkSomeSL _ xs) = toList xs

Here, SomeSL wraps the SizedList type from my question along with a singleton nat, allowing functions to access the length through the SNat n.
Justin Le's series of blog posts about singletons was very helpful: https://blog.jle.im/entry/introduction-to-singletons-1.html

A: Your signature for fromList says it works for any type n :: Nat. But the first equation returns Nah, which requires n to be type 0.
So fromList needs to be a method of a class that can despatch on the type of n.
But you're trying to despatch on the value of the second argument to fromList -- that is, on the list being empty or not -- a dependent type. The Singletons library/technique is to fake dependent types in Haskell. And that's about where my knowledge runs out. So I use Peano Nats S Z with instances, and not with GADTs.


text:
Q: How to add lightbox in a single html file? I tried lightbox out and everything works fine with it on my home pc.
But now, I wonder if it's possible to add lightbox in a single html file.
I used three different folders for it (css, js, html).
But now I want to add it only in the html file.
For css I can put the code in
For js I can add it in  normaly, but this doesn't work for me.
The js code is from the lightbox site:

"(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory); .......... etc"

I want to run it online and have only space for an one pager (so I can't add separate folders like css and js, that's why I have to put everthing in one html folder).

A: Add it in a <script> tag:
<script>
  /* lightbox code from file here */
</script>

Depending on the lightbox execution you may want to put it in the document <head> or just above the close </body> tag.


text:
Q: Fix fragment sizes android I have two fragments. Both contains some buttons and list views. And I am displaying these two fragments vertically in separate container. But if the list view contains more items, the below fragment goes down. How can we display two fragments with fixed sizes? i.e. screen should be divided into two.

A: In this example the top container will cover 70% of the screen and the bottom 30%.
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100">

    <FrameLayout android:id="@+id/container_top"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="70"/>

    <FrameLayout android:id="@+id/container_bottom"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="30"/>

</LinearLayout>


text:
Q: In php, how do I load txt file as a string? I have a text file that contains paragraphs of text.  I want to load it as a string in php, and then collect all the e-mail addresses within it as an array.  However, how do I initially load the text file contents as the string?  Restated, I have
$string = **WITHIN TEXT FILE "user@domain.com MIME-Version: bla bla bla user2@example.com";
$matches = array();
$pattern = '/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/'
preg_match($pattern, $string, $matches);

How do I load the text from the text file into the string variable?
Thanks in advance!

A: The simplest way is file-get-contents!
$file_content = file_get_contents('/path/to/file');

A: $fileContent = file_get_contents($url);

Check the reference at http://php.net/manual/en/function.file-get-contents.php

A: $lines = file('file.txt');

foreach ($lines as $line) {
  // ...
}

A: file_get_contents


text:
Q: failed password for installing homebrew I am trying to download homebrew but the default of terminal ask me type in password and I don't know exactly the password for that. Could anyone tell me how to deal with that?
    Last login: Sun Oct 27 17:32:17 on ttys000
`111-250-68-247:~ louisa$ ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go)
==> This script will install:
    /usr/local/bin/brew
    /usr/local/Library/...
    /usr/local/share/man/man1/brew.1

Press ENTER to continue or any other key to abort
==> /usr/bin/sudo /bin/mkdir /usr/local

WARNING: Improper use of the sudo command could lead to data loss
or the deletion of important system files. Please double-check your
typing when using sudo. Type "man sudo" for more information.

To proceed, enter your password, or type Ctrl-C to abort.

Password:
Failed during: /usr/bin/sudo /bin/mkdir /usr/local
111-250-68-247:~ louisa$

A: It's asking for the password of your account but it doesn't seem to be an authentication issue. You probably need to enable the root account

A: Use the password for the User that you are currently logged in as. Worked for me


text:
Q: How to replace all instances of (multiple) whitespace characters (blanks, tabs, newlines) by single blanks in C using array? I tried using getchar() to solve the problem and it works, but now I am using fgets() to get the text line by line and the whole text is stored in an array. I want to replace all instances of multiple whitespace characters including blanks, tabs, and newline by a single blank.
This is what I did using getchar():
 int c;

while ((c = getchar ()) != EOF
{
    if (c == '\r') continue;
    if (c == '\n') {
        putchar (c);
        while ((c = getchar ()) == '\n' || c == '\r') {}
        if (c != EOF) ungetc (c, stdin); else break;
        continue;
    }
    if (c == ' ' || c == '\t') {
        putchar (' ');
        while ((c = getchar ()) == ' ' || c == '\t') {}
        if (c != EOF) ungetc(c, stdin); else break;
        continue;
    }
    putchar (c);
}
return 0;

}
Now, I am trying to do this:
while (1) {
    if (fgets(line,max_len, stdin) == NULL) break;
    for (int i=0;i<strlen(line);i++){
        text[n++]=line[i];
    }
}

Where each the text is stored in an array from where I want to filter it.

A: *

*dont repeat yourself: you need only one getc() and one putc()

*while in the loop, you only need to remember whether the previous outputted character was a blank.

*break and continue exist for a reason.

int count;

for(count=0; ; ) {
    int ch;
    ch = getc(stdin);
    if( ch == EOF) break;
    switch(ch) {
    case ' ':
    case '\t':
    case '\n':
    case '\r':
            if(count++) continue;
            ch = ' ';
            break;
    default:
            count=0;
            break;
            }
    putc(ch, stdout);
    }

Similar logic for rewriting a character buffer:

char line[100];
while ( fgets(line,sizeof line, stdin) ) {
    unsigned dst,src,count;
    for (count=dst=src=0; line[dst]=line[src++];){
        switch(line[dst]) {
        case ' ':
        case '\t':
        case '\n':
        case '\r':
            if(count++) continue;
            line[dst++] = ' ';
            break;
        default:
            dst++;
            count=0;
            break;
            }
        }
    fputs(line,stdout);
    }

As you can see, you don't need the buffer, it will only complicate things.


text:
Q: Custom post type suddenly stoped working after WordPress 5 update I build a simple plugin that has a CPT and 1 metabox section that collect extra information from admin. It was working fine in the old version but when i just updated it to WordPress 5 it stopped working.
I tried to figure it out and when I comment the Meta Box input fields then my CPT works fine. Otherwise, I got the following error.

A post type mismatch has been detected.

I event don't find any help over the web if i missed something.
These are my metabox codes:
// add_action('add_meta_boxes', array($this, 'answer_meta_action'));
add_action('admin_menu', array($this, 'answer_meta_action'));

public function answer_meta_action() {
    add_meta_box(
        'ttl-to-edit',
        __('Edit In Response To', 'ttl-p'),
        array($this, 'response_to_edit'),
        'ttl', // Custom Post Type
        'normal',
        'high'
    );
}

public function response_to_edit()
{
    $post_types = get_post_types();
    ?>

                Post Type:

                <select name="post_type" style="width: 200px;margin-right:20px;">
                    <option value="">- Select -</option>
                    <?php foreach( $post_types as $post_type ): ?>
                        <option value="<?php echo $post_type ?>"><?php echo $post_type ?></option>
                    <?php endforeach; ?>
                </select>

    <?php
}

CPT Register:
add_action('init', array($this, 'init'));
public function init() {

    $labels = array(
        'name' => _x( 'Question', 'Post Type General Name', '' ),
        ....
    );

    $args = array(
        'labels'             => $labels,
        'description'        => __( 'Questions', '' ),
        'public'             => false,
        'publicly_queryable' => false,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'menu_position'      => 5,
        'menu_icon'          => 'dashicons-format-status',
        'query_var'          => true,
        'rewrite'            => array('slug'=>'question'),
        'capability_type'    => 'post',
        'capabilities'       => array(
            'create_posts'       => 'do_not_allow',
        ),
        'map_meta_cap'       => true,
        'has_archive'        => 'questions',
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array( 'title', 'editor' ),
    );

    register_post_type( 'ttl', $args );
    flush_rewrite_rules();
}

A: OK, I had to debug it and... Everything is just fine with your code. Almost everything.
When I click the Publish button, I get that error:

A post type mismatch has been detected

And if you'll take a look at your form, you'll see why...
In your form you have this field:
<select name="post_type" style="width: 200px;margin-right:20px;">

post_type name is already used for different purposes. So your field overwrites it and is causing the error.
There are some names that you should be avoided, when you create your own meta boxes. And the best idea is to prepend your fields with some prefix to make sure, you're not causing any conflicts.
So if you add ttl-to-edit meta box, I'd call all the fields like ttl-to-edit-post_type or something like this. Sometimes it's convenient to put them in an array like ttl_to_edit[post_type].
PS. You should NEVER put flush_rewrite_rules in init hook - it will cause major performance issues.

*

*Flushing the rewrite rules is an expensive operation, there are
  tutorials and examples that suggest executing it on the 'init' hook.
  This is bad practice. It should be executed either on the 'shutdown'
  hook, or on plugin/theme (de)activation.

*Flush rules once (it's better to store the state in option, instead of
  activation or deactivation, because on MultiSite they are
  useless), or when you know that the rewrite rules need to be changed.
  Don't do it on any hook that will triggered on a routine basis.


text:
Q: Passing value from MVC View to Controller using ajax I am developing web app with asp.net core 3.1.
I have an ajax call sends a ConsultViewModel object to my controller, but in controller it is getting null. I don't understand my error. I changed the ajax "data: JSON.stringify({consultView: consultView})" to "data: JSON.stringify(consultView)" but error persist.
How do i solve this problem?
My code is just as follow:
ViewModel
public class ConsultViewModel
{
    public int Id { get; set; }
    [Range(1, int.MaxValue, ErrorMessage = "Select a Department")]
    public int DepartmentId { get; set; }
    [Required]
    public string Description { get; set; }
    public string Date { get; set; }
    public IEnumerable<SelectListItem> Department { get; set; }
}

View
@model MyApp.AppWeb.Models.ConsultViewModel;

Edit

    <form asp-action="Edit">

        <input type="hidden" asp-for="Id" />

            <select asp-for="DepartmentId" asp-items="Model.Department" class="form-control"></select>

            <input asp-for="Date" class="form-control" disabled />

            <textarea asp-for="Description" class="form-control" cols="40" rows="5"></textarea>

            <input type="button" class="btn btn-primary" value="Save" id="btnEdit"/>

    </form>

Scripts
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

}
[HttpPost]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(ConsultViewModel consultView)
    {
        if (ModelState.IsValid)
        {
            //More code..

            return Json(new { success = true, message = "Done." });
        }

        return View(consultaView);
    }

Thank!

A:
I have an ajax call sends a ConsultViewModel object to my controller, but in controller it is getting null.

You can try to modify the code to stringify your JavaScript object consultView  directly, need not to construct a new JavaScript object {consultView: consultView}.
data: JSON.stringify(consultView),

Besides, apply [FromBody] attribute to parameter like below.
public async Task<IActionResult> Edit([FromBody]ConsultViewModel consultView)
{

Testing data that I sent

Posted data can be bound as expected


text:
Q: Context classloader and issue with loading resource within one of the dependencies I'm facing one odd issue with loading a properties file from a static class/method which is inside a jar file. This jar file is part of a spring boot application. So basically following is the structure
API-springboot.jar
|
|---- BOOT-INF/lib/my-other.jar
      |
      |----- app.properties
      |----- com/foo/bar/blah/Utils.class --> Static class loading app.properties

*

*Here Utils.class is a collection of various static utility methods.

*Util.class has a static method which loads the app.properties. Below is the code of Utils
package com.foo.bar.blah;

public final class Utils {
    private static final String PROPS_FILE = "app.properties";
    private static final Properties props = loadProperties();

    public static String doSomething(String str) {
        // ... some logic by reading props
        return "blah";
    }

    private static Properties loadProperties() {
        LOG.debug("Loading properties {}", PROPS_FILE);
        InputStream resourceAsStream = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream(PROPS_FILE);

        if (resourceAsStream == null) {
            throw new RuntimeException("Can't load the properties file " + PROPS_FILE);
        }

        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(resourceAsStream, StandardCharsets.UTF_8));
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

        return properties;
    }
}

*

*Now when the Utils.doSomething is invoked for the first time, loadProperties will be invoked and load app.properties (at the root of the classpath)

*This works fine locally (macOS & OpenJDK 11.0.8) and also on my test env (RHEL 7 and OpenJDK 11.0.9)

*When deployed on UAT env, it cannot find app.properties and throws an exception as defined in the method
    if (resourceAsStream == null) {
        throw new RuntimeException("Can't load the properties file " + PROPS_FILE);
    }

*

*Spring boot version is v2.3.5.RELEASE

*Below is what I've checked till now

*

*On UAT, I have the same JRE as on test

*UAT and test has the same version of the application deployed via CI/CD pipeline (Jenkins/Artifactory etc)

*On UAT, I extracted my application's spring-boot jar file and can see the my-other.jar under BOOT-INF/lib

*I verified that my-other.jar has the app.properties in the root and also the Utils.class is present

*I created a sample test class on one of the UAT servers which simply calls Utils.doSomething("blah") with correct classpath set and it can load the app.properties from the jar and shows expected result. But the issue comes when it's invoked from the spring-boot application.

*JRE version is the same on UAT and test and spring-boot application is using the right JRE.

    openjdk version "11.0.9" 2020-10-20 LTS
    OpenJDK Runtime Environment 18.9 (build 11.0.9+11-LTS)
    OpenJDK 64-Bit Server VM 18.9 (build 11.0.9+11-LTS, mixed mode, sharing)

Question: What is causing this behaviour? Am I missing anything? Spent 3 hours with no success.