text:
Q: Why sometimes snackbar is failing Please help to explain why sometimes my SnackBar is showing an error. I don't understand at which circumstance the issue will come. I just want to point also that even though it is showing the error, in the app itself, it is working fine.
Here's my code:
void showFailedSnackBar(String s) {
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

Here's the error:
E/flutter ( 7879): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
E/flutter ( 7879): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.

A: Try to check if the widget is still mounted in the three:
void showFailedSnackBar(String s) {
    if (mounted) {
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }

  }

A: In your function showSnackbar, besides the String you could also pass a BuildContext context variable, so you know which context you pass e.g.
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

You could save the context of the scaffold that you are sure it exists in a provider in order to pass it around where you need it.

A: https://velog.io/@namtaehyun/Flutter-This-widget-has-been-unmounted-so-the-State-no-longer-has-a-context
define global navigator context in main.dart, and use it everywhere
// main.dart

final navigatorKey = GlobalKey<NavigatorState>(); // define global key

void main() => runApp(
  MaterialApp(
    ...
    navigatorKey: navigatorKey, // propagate to all descendant contexts
  ),
);

// other.dart

void showMyDialog() {
  showDialog(
    context: navigatorKey.currentContext, // reference global context
    builder: (context) => ...
  );
}


text:
Q: Gps Navigation Example Android JAVA I want to make a navigation system. like when i need turn left to go my home , my navigation is saying to me "Turn Left" . Do any source for this example or can anyone help me for this ?

A: Simply use a service like mapquest.
It's fairly easy to parse the return,  you have a series of way points you can plot and when the GPS distance to that way point is less than x meters then read the announcement and start monitoring the proximity of the next one.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doubts about Django models primary_key and UniqueConstraint for composite primary key Usually primary key means also unique (and more conditions like not null, etc.). If I have UniqueConstraint with 2 fields, including the primary key, I have 2 unique conditions (one because the primary key and another because the constraint). So that's is not the same than having a composite primary key with only one unique condition. For example, with this code:
class MyClass (models.Model):
    field1=models.IntegerField(primary_key=True)
    field2=models.IntegerField()
    UniqueConstraint(fields=['field1', 'field2'], name='ConstraintName')

Can I insert these values (1,1) and (1,2) since the field1 value is repeated and the primary key should be unique? In that case, what's the real meaning of primary key on Django models? Doesn't it imply a unique condition?
Thanks a lot and regards.


text:
Q: Intersection point of parametric lines in $\mathbb{R}^3$ I have the following two parametric equations of lines:
$$\begin{cases} x = -t + 1 \\ y = t + 3 \\ z = -6t \end{cases} \quad \land \quad \begin{cases} x = 2s + 4 \\ y = -s \\ z = 2s + 1 \end{cases}$$
I want to examinate their mutual position, that is, I want to find out if they intersect.
$$\begin{cases} -t + 1 = 2s + 4 \\ t + 3 = -s \\ -6t = 2s + 1 \end{cases}$$
$$\begin{cases} -t + 1 = 2s + 4 \\ -t - 3 = s \\ -6t = 2(-t-3) + 1 \Rightarrow -6t = -2t - 5 \Longrightarrow t = \frac{5}{4}\end{cases}$$
$$-\frac{5}{4} - 3 = s \Longrightarrow s = - \frac{17}{4}$$
So they intersect for $t = \frac{5}{4} \lor s=-\frac{17}{4}$.
Plugging $t$ into first equation:
$$\begin{cases} x = -\frac{5}{4} + 1 \\ y = \frac{5}{4} + 3 \\ z = -6 * \frac{5}{4} \end{cases}$$
Point $P(-\frac{1}{4}, \frac{17}{4}, -\frac{15}{2})$ is the intersection point.
Thing is, I don't think that's true. I sketched those lines in parametric plotter and they look like this:

They look like skew to me. What went wrong?

A: Adding the first two equations, $4=s+4$ and obviously $s=0$, then $t=-3$. As this doesn't fit with the third, there is no intersection.
You didn't check that your $s,t$ values satisfy all three equations.

A: Notice that $t = \frac{5}{4}$ and $s = -\frac{17}{4}$ does not satisfy the equation $-t+1 = 2s+4$. Therefore, this equation system has no solution and there are no intersection points.


text:
Q: ejabberd: inspect Mnesia tables? I'm digging into ejabberd but I can't find a way to inspect its Mnesia tables.
Is there something like the MySQL shell to inspect tables?

A: You may use the Table Visualizer, in module tv.
It can help examine ets tables and mnesia tables. You can simply start it on any connected node (e.g. with "ejabberdctl debug"), with:
 tv:start().

A: Just go to folder where ejabberd is installed.Then go to bin folder and type command ./ejabberdctl dump_table file_name_in_which_table_will_be_dumped Table_Name.
This file will be created in database/ejabberd@localhost/dump_table file_name_in_which_table_will_be_dumped


text:
Q: Time-dependent manifolds I'm studying Classical Mechanics, and in some cases the particles in the study are constrained to move in a certain manifold, which changes with time.
I've looked for bibliography about time-depending manifolds, or something similar I could apply to this study, but I haven't found anything yet,
so I'd greatly appreciate any bibliographical suggestion.

A: Any book dealing with non-autonomous differential equations (so pretty much any book) should fit the bill.  If you want better understanding of just manifolds Tu's Introduction to Manifolds is a reasonable choice.  For ODEs I would recommend Ordinary Differential Equations with Applications by Chicone (very theoretically rigorous and does most of its work in Banach Spaces).  For PDE, one text to consider is Taylor's Partial Differential Equations: basic theory (Springer).  If you want a treatment specifically in the language of manifolds, and taking a more differential geometry approach Pressley's Elementary Differential Geometry (Springer) is a pretty solid (and reasonably priced) introduction.


text:
Q: Woocommerce: Display only option label (and not price) in mini-cart and on cart and checkout pages I'm using Gravity Form Product add-ons with Woocommerce. I have option fields where I include the option name and price as the label (so the price is clearly visible to the customer). This means, however, that the mini-cart, cart and checkout pages show the label as well as the the price and creates a bit of clutter. The images I've linked to below should show what I mean:
http://tinypic.com/r/15q5ks3/9
http://tinypic.com/r/ege6hs/9
I want to remove the price and parenthesis.
Can anyone help? :)
Darren

A: Not sure what is your template code. But in quick JS script you could solve this in front end.
Add this JS to your product page:
jQuery(document).ready(function(){
  jQuery( ".mini_cart_item" ).each(function( index ) {
    html = jQuery(this).html();
    html = html.replace(/ *\([^)]*\) */g, "");
    jQuery(this).html(html);
  });
})


text:
Q: No resource found that matches the given name (at 'label' with value) So I ran into this problem trying to get my signed APK, I have referenced it in my strings.xml and have tried deleting it and rewriting it nothing seems to work this is my Manifest.XML. I am sort of a noob at coding and stuff so a simple and thorough explanation would help
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chattr.chattr"
    android:versionCode="1"
    android:versionName="1.0" >

     <uses-sdk
         android:minSdkVersion="15"
         android:targetSdkVersion="21" />

        <permission android:name="android.permission.INTERNET" />
        <permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <!-- To auto-complete the email text field in the login form with the      user's emails -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.READ_PROFILE" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.chattr.chattr.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.chattr.chattr.LoginActivity"
            android:label="@string/title_activity_login"
            android:windowSoftInputMode="adjustResize|stateVisible" >
        </activity>
        <activity
            android:name="com.chattr.chattr.ListUsersActivity"
            android:label="@string/title_activity_list_users" >
        </activity>
        <activity
            android:name="com.chattr.chattr.MessagingActivity"
            android:label="@string/title_activity_messaging" >
        </activity>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

Here is my styles. xml
    <?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">MessagingTutorial</string>
    <string name="login_activity_label">Sinch Messaging Tutorial</string>
    <string name="username">USERNAME</string>
    <string name="password">PASSWORD</string>
    <string name="title_activity_list_users">ListUsersActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="message_elipses">Message...</string>
    <string name="logout">Logout</string>
    <string name="messaging_activity">Messaging</string>

</resources>

A: Your manifest references string resources (@string/foo) that are not present in a resource file under res/values. For example, strings title_activity_login and title_activity_messaging are missing from the resource file you posted.


text:
Q: Removing asymptotes from y=sec(x) I am trying to draw the graph of y = sec(x ), see below
\begin{tikzpicture}[scale=1]
\begin{axis}[ymax=10,ymin=-10]
\addplot[color=red,domain=-360:360,samples=101,unbounded coords=jump]
{sec(x)};
\draw[ultra thin] (axis cs:0,\pgfkeysvalueof{/pgfplots/ymin}) -- (axis
cs:0,\pgfkeysvalueof{/pgfplots/ymax});
\draw[ultra thin] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis
cs:\pgfkeysvalueof{/pgfplots/xmax},0);
\end{axis}
\end{tikzpicture}

This gives the below output:

How do I remove the vertical red lines from  this?

A: You can do this:
\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}[scale=1]
\begin{axis}[ymax=10,ymin=-10]
\addplot[color=red,domain=-360:360,samples=400,restrict y to domain=-15:15]
{sec(x)};
\draw[ultra thin] (axis cs:0,\pgfkeysvalueof{/pgfplots/ymin}) -- (axis
cs:0,\pgfkeysvalueof{/pgfplots/ymax});
\draw[ultra thin] (axis cs:\pgfkeysvalueof{/pgfplots/xmin},0) -- (axis
cs:\pgfkeysvalueof{/pgfplots/xmax},0);
\end{axis}
\end{tikzpicture}
\end{document}

With the option restrict y to domain=-10:10 it should give the result you want... but the samples have to be huge for this to work... So I changed it to -15:15 and just increased a little bit the samples. The output is like yours without the asymptotes.

A: what about drawing graph by 90 degree domains segments?
    \documentclass[tikz, margin=3mm]{standalone}
    \usepackage{pgfplots}
    \pgfplotsset{compat=1.15}

    \begin{document}
\begin{tikzpicture}
\begin{axis}[
    ymax=10,ymin=-10,
    samples=30
            ]
    \foreach \i in {-360,-270,...,270}
\addplot[color=red,domain=\i:\i+90] {sec(x)};
\draw[ultra thin]
    (0,\pgfkeysvalueof{/pgfplots/ymin}) -- (0,\pgfkeysvalueof{/pgfplots/ymax})
    (\pgfkeysvalueof{/pgfplots/xmin},0) -- (\pgfkeysvalueof{/pgfplots/xmax},0);
\end{axis}
\end{tikzpicture}
    \end{document}


text:
Q: JavaScript, Execute function after function mainFunc(){
 firstFunc();
 SecondFunc();
 Playball();
}

function Playball () {

var paper = new Raphael(0, 0, 800, 500);
var backGround = paper.rect(0, 0, 800, 500);

var ball = paper.circle(400, 0, 30);
ball.attr({fill: "blue"});

function step1() {
    ball.animate({cx: 400, cy: 600}, 2500);
}

step1();
};

This is what I've written so far, I have more functions that need to be executed consecutively. I'm aware that I can use a simple callback function but I can't get it work, Step2 never executes. Below is what I've tried. Also is there a better method that I can use in this scenario given that I have multiple functions. I'm unable to use the SetTimeout since my main function is triggered on a click event.
function Playball (callback) {

var paper = new Raphael(0, 0, 800, 500);
var backGround = paper.rect(0, 0, 800, 500);

var ball = paper.circle(400, 0, 30);
ball.attr({fill: "blue"});

function step1() {
    ball.animate({cx: 400, cy: 600}, 2500);
}

step1();
return true;
};

Playball(step2());

A: I assume you'd like step2 to start after the animation of step1,so does this work?
function Playball (callback) {

  var paper = new Raphael(0, 0, 800, 500);
  var backGround = paper.rect(0, 0, 800, 500);

  var ball = paper.circle(400, 0, 30);
  ball.attr({fill: "blue"});
  //http://dmitrybaranovskiy.github.io/raphael/reference.html#Element.animate
  function step1() {
    ball.animate(
      {cx: 400, cy: 600}//params
      , 2500            //number of milliseconds for animation to run
      ,undefined        //easing type
      ,callback         //callback function. Will be called at the end of animation
    );
  }

  step1();
  return true;
};

Playball(step2);

An example fiddle can be found here.


text:
Q: Fixed-size array of objects and sub-objects on the heap I've searched and searched but haven't found anything that really clears up my confusion.
I'm representing a grid, and have two classes, e.g.:
class Term {
   ...
};

class GridPoint{
   Term a;
   Term b;
   Term c;
   ...
};

I would like to have a large, fixed-size array on the heap, where each element of the array is a GridPoint, itself containing multiple Terms.
However, the following example will not compile:
GridPoint* pGrid = new GridPoint[100][100];

According to gcc:

error: cannot convert 'GridPoint (*)[100]' to 'GridPoint*' in initialization

A: First I would like to suggest not using new and delete in modern C++, instead use smart pointers or containers from the standard library that encapsulates this as e.g. std::vector.
That being said, to get your example to work you have to initialize an array of arrays in a loop like so:
GridPoint** pGrid = new GridPoint*[100];
for (std::size_t i = 0; i != 100; ++i) {
    pGrid[i] = new GridPoint[100];
}

// Do something...

for (std::size_t i = 0; i != 100; ++i) {
    delete[] pGrid[i];
}
delete[] pGrid;

For a better alternative simply use std::array or std::vector:
std::array<std::array<GridPoint, 100>, 100> pGrid;

Note: std::array encapsulates a static array that it uses to store its data. This means that if you allocate a std::array object with automatic storage duration its data will not be dynamically allocated (the data will not be on the "heap").
std::vector will however store its data using dynamic allocation.


text:
Q: Force Close when following ASyncTask Example I'm getting a force close error when attempting to follow this tutorial:
http://www.bango29.com/go/blog/2011/android-asynctask-is-a-beauty-part-2
Any suggestions? I'm really not sure where I went wrong in this.
MY SOURCE:
public class HttpGetAndroidExample {

    // The url of the website. This is just an example

    private static final String webSiteURL = "http://www.supercars.net/gallery/119513/2841/5.html";

    // The path of the folder that you want to save the images to

    private static final String folderPath = "<FOLDER PATH>";

    public static void main(String[] args) {

        try {

            // Connect to the website and get the html

            Document doc = Jsoup.connect(webSiteURL).get();

            // Get all elements with img tag ,

            Elements img = doc.getElementsByTag("img");

            for (Element el : img) {

                // for each element get the srs url
                String src = el.absUrl("src");

                System.out.println("Image Found!");

                System.out.println("src attribute is : " + src);

                getImages(src);

            }

        } catch (IOException ex) {

            System.err.println("There was an error");

            Logger.getLogger(HttpGetAndroidExample.class.getName()).log(Level.SEVERE,
                    null, ex);

        }

    }

    private static void getImages(String src) throws IOException {

        String folder = null;

        // Exctract the name of the image from the src attribute
        int indexname = src.lastIndexOf("/");

        if (indexname == src.length()) {

            src = src.substring(1, indexname);

        }

        indexname = src.lastIndexOf("/");

        String name = src.substring(indexname, src.length());

        System.out.println(name);

        // Open a URL Stream

        URL url = new URL(src);

        InputStream in = url.openStream();

        OutputStream out = new BufferedOutputStream(new FileOutputStream(
                folderPath + name));

        for (int b; (b = in.read()) != -1;) {

            out.write(b);

        }

        out.close();

        in.close();

    }

}

Logcat:
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapUtilization:0.25
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapIdealFree:8388608
07-18 17:22:06.449: D/ActivityThread(11404): setTargetHeapConcurrentStart:2097152
07-18 17:22:06.469: W/dalvikvm(11404): threadid=1: thread exiting with uncaught exception (group=0x41e1f438)
07-18 17:22:06.469: E/AndroidRuntime(11404): FATAL EXCEPTION: main
07-18 17:22:06.469: E/AndroidRuntime(11404): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.httpgetandroidexample/com.example.httpgetandroidexample.HttpGetAndroidExample}: java.lang.ClassCastException: com.example.httpgetandroidexample.HttpGetAndroidExample cannot be cast to android.app.Activity
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2012)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread.access$700(ActivityThread.java:139)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.os.Looper.loop(Looper.java:137)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread.main(ActivityThread.java:4918)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at java.lang.reflect.Method.invokeNative(Native Method)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at java.lang.reflect.Method.invoke(Method.java:511)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at dalvik.system.NativeStart.main(Native Method)
07-18 17:22:06.469: E/AndroidRuntime(11404): Caused by: java.lang.ClassCastException: com.example.httpgetandroidexample.HttpGetAndroidExample cannot be cast to android.app.Activity
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
07-18 17:22:06.469: E/AndroidRuntime(11404):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2003)
07-18 17:22:06.469: E/AndroidRuntime(11404):    ... 11 more

MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.httpgetandroidexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.httpgetandroidexample.HttpGetAndroidExample"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

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

</manifest>

A: There are two issues:
In manifest, you've declared the HttpGetAndroidExample class as an activity. Contradictory to that, the HttpGetAndroidExample class does not extend the Activiy class. So, its not an activity. That's why the exception HttpGetAndroidExample cannot be cast to android.app.Activity. Either extend it to be an Activity and create the required functions or remove it from the manifest if its not an activity.
Also, there is no where on the tutorial link I could see this class.


text:
Q: How to use Client Key instead of Rest Api Key for Android on Parse.com Rest Api requests In Parse.com Rest API documentation it says this:

You should not use the REST API Key in client apps (i.e. code you distribute to your customers). If the Parse SDK is available for your client platform, we recommend using our SDK instead of the REST API. If you must call the REST API directly from the client, you should use the corresponding client-side Parse key for that plaform (e.g. Client Key for iOS/Android, or .NET Key for Windows/Xamarin/Unity).

In my retrofit api I have the following code with header:
  @Headers({"X-Parse-Application-Id: " + ParseEndPointConfig.PARSE_APPLICATION_ID, "X-Parse-REST-API-Key: " + ParseEndPointConfig.PARSE_CLIENT_KEY})
  @POST("classes/Xxx")
  Observable<XxxParseObject> createXxx(@Body XxxParseObject circle);

As stated in the docs, using Rest Api Key is not recommended. It is suggested to use Client key for Android. How should the header look like if I used Client key for authentication? Is there any example on using Client key instead of Rest Api key for client side applications?

A: Short answer: use the header X-Parse-Client-Key in your REST call.
Full explanation: When you look at the Parse REST docs, you frequently see examples like this:
curl -X POST \
  -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
  -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
  -H "Content-Type: application/json" \
  -d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
  https://api.parse.com/1/classes/GameScore

Note how the parse headers start with X-Parse-. I previously needed to figure out how to use dotNET key for parse-push-plugin. On a hunch, I searched the dotNET SDK for X-Parse-, and found the header to be X-Parse-Windows-Key.
Doing the same thing with the Java SDK, you would find the following declarations in ParseRESTCommand.java
static final String HEADER_APPLICATION_ID = "X-Parse-Application-Id";
static final String HEADER_CLIENT_KEY = "X-Parse-Client-Key";


text:
Q: Why does seq() create both int and num vectors whereas c() never creates int vectors? I can't figure out why seq() can output different classes depending on if decimal points are present in the elements, whereas c() always creates a num vector regardless of presence or absence of decimals.
For example:
seqDec <- seq(1, 2, 0.5) # num vector
cDec <- c(1, 1.5, 2) # num vector
seqInt <- seq(1, 5) # int vector
cInt <- c(1, 2, 3, 4, 5) # num vector

A: c creates a vector by concatenating the elements you give it. By contrast seq actually constructs a sequence by generating new numbers based on specific parameters.
So in the case of c(1, 2, 4, 5), since the arguments are numeric, so is the result (class(1) is numeric, not integer!). You could generate an integer vector by providing integers:
intvec = c(1L, 2L, 3L, 4L, 5L)

Cumbersome. But possible.
With seq, if you don't provide a step size (by parameter), the function defaults to generating integral values; in this regard it's equivalent to the : operator:
intvec = 1 : 5

In fact, if you don't provide a by or length.out argument, then seq(from, to)internally executes from : to.


text:
Q: Requested URL not found Code sample is Swift 3.0 running in Xcode 8(β3).
This Weather Underground URL (when MyKey is replaced with a valid key) returns a JSON string containing the current weather at the given location...  http://api.wunderground.com/api/MyKey/conditions/q/51.3276,-1.0022.json
The code below should do the same thing but instead throws an error ("The requested URL was not found on this server.", details at bottom).
Can anyone see what I'm missing in the code?
private let key = "MyKey" // Substitute a valid Weather Underground key here.

@IBAction func fetchWeather() {
    let session = URLSession.shared
    let url     = URL(fileURLWithPath: "http://api.wunderground.com/api/\(key)/conditions/q/51.3276,-1.0022.json")

    let handler = { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
        guard let data = data, let response = response, error == nil else {
            print("\nError: \(error?.description)\n")
            return
        }
        print("\nData: \(data)\n")
        print("\nResponse: \(response)\n")
    }

    let task    = session.dataTask(with: url, completionHandler: handler)
    task.resume()
}

Error: Optional("Error Domain=NSURLErrorDomain Code=-1100 \"The requested URL was not found on this server.\" UserInfo={NSUnderlyingError=0x600000442520 {Error Domain=kCFErrorDomainCFNetwork Code=-1100 \"(null)\"}, NSErrorFailingURLStringKey=file:///http:/api.wunderground.com/api/MyKey/forecast/q/51.3276,-1.0022.json, NSErrorFailingURLKey=file:///http:/api.wunderground.com/api/MyKey/forecast/q/51.3276,-1.0022.json, NSLocalizedDescription=The requested URL was not found on this server.}")


text:
Q: Combining 2 lists of diffrent types into 1 based on an ID using LINQ Hello so I'm trying to combine these 2 lists into 1.
List<Entry> testing = new List<Entry>();
List<Tool> yes = new List<Tool>();

foreach (var p in _context.Tool
   .Join(_context.Entry,
         o => o.ToolId,
         od => od.FktoolId,
         (o, od) => new { o.Name, od.Measure, od.RunDate, od.User, od.V }))
{
    testing.Add(new LogEntries {
      Measure = p.Measure,
      V = p.V,
      RunDate = p.RunDate,
      User = p.User});

    yes.Add(new Tool {
      Name = p.Name });
}

So I'm taking these 2 lists because I want the Name from one table to join with the other table. I'm then taking the list and turning it into JSON
ViewBag.Testing = JsonConvert.SerializeObject(testing);

I'm only getting the data from testing list but I want the Name from list "yes" into list "testing" based on the tool ids.
So can I just push the name into the list or is there a way to merge them. Since they are diffrent types I can't concat or intersect.
So the Data I'm pulling now is

[{ Measure : "1",
V : 3,
RunDate: "08/12/19",
User: "Test User"}]

And I'm wanting it to look like this

[{ Measure : "1",
V : 3,
RunDate: "08/12/19",
User: "Test User",
Name: "Dragon"}]

A: In your Join statement you are already creating combined objects.  Why don't you just put those combined objects in a list and serialize that?
var list = _context.Tool
    .Join(_context.Entry,
          o => o.ToolId,
          od => od.FktoolId,
          (o, od) => new { od.Measure, od.V, od.RunDate, od.User, o.Name })
    .ToList();

ViewBag.Testing = JsonConvert.SerializeObject(list);


text:
Q: Want to increment 1 level for every 100 points scored, level counter not working Basically, I want to increment 1 "level" every time 100 "points" are scored. The points work fine, but the levels will not increment for every 100 points. The problem exists in this small bit of code. Any ideas?
if (my.collisions()) {
                _total_points += 1;
                my.displayPoints();

                if (total_points >= 100) {
                  _total_levels += 1;
                  my.displayLevels();
                }
            }

Here are my displayPoints and displayLevels functions
        my.displayPoints = function () {
            gcontext.clearRect(0, 0, 200, 100);
            gcontext.fillStyle = "#ffffff";
            gcontext.fillRect(0, 0, 200, 100);
            gcontext.font = "30px Arial";
            gcontext.fillStyle = "#000000";
            gcontext.fillText("Score: " + _total_points, 10, 50);

        };

        my.displayLevels = function () {
            gcontext.clearRect(100, 100, 200, 100);
            gcontext.fillStyle = "#ffffff";
            gcontext.fillRect(0, 100, 200, 100);
            gcontext.font = "30px Arial";
            gcontext.fillStyle = "#000000";
            gcontext.fillText("Level: " + _total_levels, 10, 150);

        };

A: Maybe you should check if modulus of _total_points and 100 are zero?
I made an example for loop to demonstrate it
let _total_points = 0;
let _total_levels = 0;

for (let index = 0; index < 500; index++) {
  _total_points += 1;
  console.log("_total_points " + _total_points);
// if _total_points can be devided by 100, and remainder is zero
  if (_total_points % 100 === 0) {
    _total_levels += 1;

    console.log("_total_levels " + _total_levels);
  }
}


text:
Q: Array List to Array File[] I have to form an ArrayList to an "normal" Array File[].
File[] fSorted = (File[]) x.toArray();

The Error: Cast Exception
Exception in thread "Thread-5" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.io.File;

How can I return the list x as File[ ]-List?
--
My function:
private File[] sortFiles(File[] files){;

    ArrayList<String> allFiles = new ArrayList<String>() ;
    for (int index = 0; index < files.length; index++)
    {
        File afile = new File(files[index].toString());
        allFiles.add(afile.getPath().toString());

    }
    java.util.Collections.sort(allFiles);

    ArrayList<File> x = new ArrayList<File>();
    for(int i = 0; i< allFiles.size(); ++i){
        x.add(new File(allFiles.get(i)));
    }
    File[] fSorted = (File[]) x.toArray();

    return fSorted;

}

A: Use:
File[] fSorted = x.toArray(new File[x.size()]);


text:
Q: Regex expression working except in dotNet I am trying to match an expression of type
field:"value"

but not
field:value

I have written
([a-z]+)\s*?:\s*?"(.+)"\s*?

and this works excepts in dotNet
Is there any reason why this might be? Something I am missing?
Edit -- I typed the question wrong (figures)
I'm trying to match
field:value

but not
field:"value"

This is the regex I have
(?<field>[a-z]+)\s*?:\s*?(?<value>[^"].+[^"])\s*?

But that's not working, it matches even what's in quotes.
Edit 2:
Below is the code --
SearchResources.StringRegexNotQuotedText is ([a-z]+)\s*?:\s*?([^"]+)\s*?
stringQuery is (what:  "Hello_bob")
All relevant things are escaped....
Regex regexNotQuoted = new Regex(SearchResources.StringRegexNotQuotedText, RegexOptions.IgnoreCase);

MatchCollection matchesNotQuoted = regexNotQuoted.Matches(stringQuery);

 // It should go into this block if the value is not in quotes
 if (regexNotQuoted.IsMatch(stringQuery))
 {

 }

A: This part: [^"].+ means: a character other than double quotes, followed by one or more characters. This means you only match sequences of at least two characters that start with non-double-quotes. You probably want [^"].*, that is, sequences of at least one character, that isn't a double quote;
Now, to the issue at hand. You're getting a match, because of this part \s*?([^"].+[^"]). The \s*? part will match no spaces because it is non-greedy (that's what the question mark means here). Then the [^"] part will match a space, .+ will match "Hello_bo and the last [^"] will match the final b. The rest of the line (") will not be captured.
You need to stop using the non-greedy operators (that's almost never what you want), and to make sure you capture everything to the end of the line, using the end-of-line anchor: $.
So, this is what I recommend you use:
(?<field>[a-z]+)\s*:\s*(?<value>[^"].*[^"])\s*$

With this C# code:
Regex re = new Regex(@"(?<field>[a-z]+)\s*:\s*(?<value>[^""].*[^""])\s*$");

A: It sounds like you want to match one or more characters other than double-quotes or whitespace, so write it just like that:
[^"\s]+

The full regex would be:
(?<field>[a-z]+)\s*:\s*(?<value>[^"\s]+)

A: works for me. Here is the code I've used:
resultString = Regex.Match(subjectString, @"([a-z]+)\s*?:\s*?""(.+)""\s*?", RegexOptions.Singleline | RegexOptions.IgnoreCase).Value;


text:
Q: Clojure Hadoop - 5 Lines of Cascalog equivalent to 300 lines of PIG? In this presentation at slides 36 and 37 - the author of Cascalog asserts that given a data set of names and ages like:
[name age]
that the query to return all the results that are greater than the average age is 300 lines of PIG.
Is this a valid assertion? How many lines of PIG is it really?
Or is the problem he's describing bigger than what I've described?
(Disclaimer - I'm a big fan of Nathan's work, of Clojure and Cascalog - I'm just trying to get some facts straight).

A: You've done a misinterpretation of what he says in this presentation.
What he means is that the implementation de "average" in PIG is 300 lines de java code, versus the 5 lines of cascalog implemented by macro predicate functionality. He wants to emphasize the power of the composition.
PD: Sorry for my bad english, I'm learning ;-)

A: I don't think that it would be 300 lines of code in PIG. PIG already have filter construct and AVG eval function. The code in PIG would be something like:
A = LOAD 'student.txt' AS (name:chararray, age:int);
B = FILTER A BY age > AVG(A.age);

NOTE: I haven't tried this code as I don't have PIG setup on my machine.

A: In regular SQL it is trivial - select count(*) from TableName where age>(select avg age from TableName)
But it require that underlying engine will be able to detect that latest select is independent subquery (otherwise it will work forever).
It should be trivial to divide it into two operators - one select avg age, and second - count these above it.

A: Choosing an aggregate operation which is already implemented in PIG probably confused the message.
One theme of those slides, as @marivas11 pointed out, is that composability of predicates is a powerful alternative to the approach of user-defined functions (UDFs) which are popular in other Hadoop abstractions.
The benefits of composability extend far beyond a relative difference in code volume:

*

*composabilty of predicates reduces "accidental complexity" as defined in Moseley/Marks 2006, which benefits software engineering costs

*the concise code which results is also quite close to stated requirements; this follows almost directly from the practice of test-driven development (TDD) since Cascalog subqueries effectively become test statements -- the Cascalog-Midje addition of facts and mocks by Sam Ritchie is quite good

*getting rid of UDFs relieves a very troublesome problem on Data teams which must develop complex workflows: crossing a language boundary from Java to Pig's DML and back to Java implies that exception handling, notifications, and other instrumentation become significantly more difficult -- especially for large-scale apps, which are difficult to troubleshoot anyway on a large cluster...  in Cascalog, all the extensions stay within the same language (even the Leiningen build script is in Clojure) so the compiler has a complete view of the workflow and can infer problems earlier than PIG.
The latter point is subtle but translates to $$ in practice. In PIG, you won't find out a number of problems until your app is running on the cluster. For a large-scale app, that implies burning money to test bugs which could have been inferred at compile time or on the Hadoop client prior to submit.


text:
Q: Python Global Variable Issue Being Set
The global variable does not 'save' after the function is done being executed. You can run the code below and see the debug output.

Main file:
from GlobalTest import *

def init():

    #call that function, should set Mode2D to True
    set2DMode(True)

    #define it as a global
    global Mode2D

    #see what the value is set to now, which is not what I set it to for an unknown reason
    print("Mode:",Mode2D)

init()

GlobalTest:
Mode2D = False

def set2DMode(mode):
    #define it as global so it uses the one above
    global Mode2D

    #set the GLOBAL variable to the argument
    Mode2D = mode

    #output of what it thinks it is, which is as expected
    print("local var mode =",mode)
    print("Mode2D =", Mode2D)

What I expect:
local var mode = True
Mode2D = True
Mode: True

Result I get:
local var mode = True
Mode2D = True
Mode: False


text:
Q: Can a too powerful battery damage a circuit? I have an IOIO board, a 13V 10A Battery (when I tested with my multimeter). For the IOIO board, 5-15V, ~10mA is enough. Can a 13V 10A Battery do wrong to the board or is it okay?

A: The current rating of a power source (your battery) is the maximum current the supply can provide.
The current rating of a power load (your IOIO board) is the amount of current it can demand, for proper operation.
Thus, if the IOIO board just requires 10 mA, and operates at a specified voltage range (5-15 Volts as mentioned), then the power supply can not force more current through the board than demanded - it will merely supply as much current as is demanded, not the maximum that it can supply.
So if the voltage values in the question are correct, then the IOIO board should be perfectly safe to operate with the battery.

A: What tells you 13V-10A is that the maximum current that the battery can deliver is 10A. Either way I don't think you have problems by overcurrents. Anyway on the Internet you can find many current limiting schemes.


text:
Q: Intuition for groups This is quite a non-standard question, certainly for mathematics, though I believe it is no less important (for me and my peers, i.e. grads).
The course I am reading so far introduced us to Groups, rings, fields, etc. in the first year, progressing to characters, reps etc in the latter years.
However, even with representation theory I still don't feel like I have a good intuition.
How do you gain intuition in such an area. I know there will be a response of doing examples, but this doesn't really help - I've done lots already.
Am I doomed.

A: I'll take a stab at this. First off, intuition in mathematics is invaluable. That being said, it is often difficult to gain a level of comfort with abstract material on an intuitive level. However, any example/picture/ect. that can give some insight is wonderful. When dealing with groups, the first thing that comes to mind for myself is symmetry. A group structure indicates a degree of symmetry in an underlying object. I am quite certain you have seen groups being described as the symmetries of regular polyhedra ect. As for representations, they are in fact meant to make such symmetries more concrete. Instead of thinking of group elements as abstract symbols, we can obtain a set of matrices which behave the same way. Representations can actually be quite intuitive in some "nice" examples. For instance, a rotation group of a geometric figure can be visualized as matrices that take the figure to itself in the plane. However, when dealing with Hilbert spaces and vector spaces over arbitrary fields, this picture becomes less intuitive. I wish I had more insight as to visualizing such concepts (this lies outside of my typical area) but from experience with other abstract concepts such as higher dimensional manifolds, the best way to gain intuition is working with these things. You don't need to be able to draw what it "looks like" per se, all you need is to be able to draw a picture that means something to you. If a concept has meaning to you then its worth something (provided its accurate of course). An excellent series of videos on Youtube from a conference celebrating the proof of the Poincare conjecture has a lecture by Bill Thurston. It might be worth looking into (even though it doesn't mention representations) because Thurston was a true believer in intuition. Hope this helps a little.

A: A group is a set $G$ with an operation $\cdot$ that combines the elements of $G$ to give an element that also belongs to $G$. In order for $(G,\cdot)$ to be a group it must satisfy the following axioms: closure, associativity, identity element, inverse element.
For me the intuitive way to think about groups is to consider the Rubik's Cube group. This group consists of all possible states the cube can be in. All of the states can be reached by performing one of the face rotations: ${F, B, U, D, L, R}$ (Front, Back, Upper, Down, Left, Right) and these are called generators of the group. The operation $\cdot$ is the composition of those rotations. The closure of this group means that after performing a sequence of rotations, we end up with one of the possible Cube's permutations. Associativity is intuitive - if we perform moves $(F \cdot U)\cdot R$ we would end up in the same state as if we performed $F \cdot (U \cdot R)$. For each move there exists an opposite move (with the same face but in the opposite direction, e.g. $F$ and $F'$) that brings you back to the initial state (inverse element) and for each state of the cube there exists an identity element $e$ that means not moving the cube at all. Now you can abstract away the whole idea of cube and perform mathematical operations on this set using composition $\cdot$ and you know that this could be translated back to the physical orientation of the cube.
Sometimes different unrelated structures (atoms, particles) express some symmetry and therefore could be viewed as a subgroup of symmetry groups, e.g the Rubik's Cube group is the subgroup of the symmetric group $S_{48}$. This allows us to use common language to solve seemingly unrelated problems.

A: To be very intuitive, representation theory makes abstract algebraic objects "concrete" by describing its elements by matrices and the algebraic operations in terms of matrix addition and matrix multiplication respectively. Roughly, it makes abstract algebra into linear algebra, which is a concrete subject.


text:
Q: How to set-up a client-server program and a database together in Java? I need to create a program that has a client, server, and a database
The client needs to input data into the database or query it via the server, I am using MySQL and JDBC to connect MySQL to my java code. I was wondering what the ideal set-up is.
For example, I am connecting to my database using the following code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class test2 {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/CovidPreventation";
        String username = "test";
        String password = "test";

        System.out.println("Connecting database...");

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            System.out.println("Database connected!");
        } catch (SQLException e) {
            throw new IllegalStateException("Cannot connect the database!", e);
        }

    }

}

I was wondering where this should really go, shall I have this in the server class or in a separate class that is connected to the server. It is the first time I do such a thing and I want my practices to be good so help is appreciated.

A: DataSource
The SQL package defines the DataSource interface. An object of that type is where you keep your database connection info such as database server address, database user name, password, and so on.
To quote the documentation:

A factory for connections to the physical data source that this DataSource object represents. An alternative to the DriverManager facility, a DataSource object is the preferred means of getting a connection.

Choose an implementation of that interface. A JDBC driver usually comes with one or more implementations specific to that particular database. You need an implementation specific to that database because various databases have various features and settings.
Return an object  of the more general type, the interface, rather than the more specific type, the concrete implementation. Doing so gives you the flexibility of swapping out the concrete class for another without breaking any calling code.
    private DataSource configureDataSource ( )
    {
        System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );

        com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() );  // Implementation of `DataSource`.
        dataSource.setServerName( "db-mysql-lon3-433-do-user-89673-1.x.db.ondigitalocean.com" );
        dataSource.setPortNumber( 24_090 );
        dataSource.setDatabaseName( "defaultdb" );
        dataSource.setUser( "scott" );
        dataSource.setPassword( "tiger" );
        return dataSource;
    }

Retain that DataSource object in your app. When needing a database connection, call DataSource#getConnection.
        String sql = "SELECT name_ from  user_ ; " ;
        try (
                Connection conn = myDataSource.getConnection() ;
                Statement statement = conn.createStatement() ;
                ResultSet resultSet = statement.executeQuery( sql ) ;
        )
        {
            while ( resultSet.next() )
            {
                String userName = resultSet.getString( "name_" );
                System.out.println( username ) ;
            }
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }

Be sure to close your open resources such as Connection, Statement, PreparedStatement, and ResultSet. Generally best to use the try-with-resources syntax to automatically close your resources.
Notice a DataSource is never "opened", so we never need close it. A DataSource merely holds the bits of info needed to ask the database server for a connection. The DataSource object itself is not a resource.
JNDI
Eventually you may want to use JNDI to obtain a DataSource object. This enables you to externalize the database configuration through a Jakarta EE server, LDAP server, etc. rather than hard-code the username, password, etc.
Under this approach, when your database changes its address or passwords, you can update the external configuration without needing to recompile your code and redeploy your app.
To quote the documentation:

An object that implements the DataSource interface will typically be registered with a naming service based on the Java Naming and Directory (JNDI) API.

For more info
See also:

*

*Implementation of JDBC DataSource in MySQL Connector/J 8

*Tutorial by Oracle, free of cost

*Why do we use a DataSource instead of a DriverManager?

A: all you need a jdbc driver, you can get it here: https://mvnrepository.com/artifact/mysql/mysql-connector-java
and add jar file to your ide
after you need to call it at your code like this:
public static Connection getConnection(String dbURL, String userName,
            String password) {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(dbURL, userName, password);
            System.out.println("connect successfully!");
        } catch (Exception ex) {
            System.out.println("connect failure!");
            ex.printStackTrace();
        }
        return conn;
    }

A: I guess you are asking about the design/architecture of the application. If that is the case then you should follow MVC architectural pattern.
** What is MVC ?**
MVC has three main components:

*

*Model

*View

*Controller

each of them has specific responsibilities.

Model
Model is responsible or maintaining data. It is actually connected to DB. So any data manipulation i.e. ADD/Update/Delete/Insert you want to do is done in model.  Basically Models only talks with Controller and gives the needed data to controller. i.e. Model never communicates with Data directly.
View
Data representation i.e. UI (Html/CSS part) is done by View. Controller gives data to View which will be show to end user. i.e. View only speaks to controller.
Controller
Controller enables interaction between views and model. It does not have to worry about business logic. It will tell the model what should be done. After receiving Data from the Model it sends it to View.


text:
Q: Fix hundreds of lines of warnings re layout constraints from DatePicker Using the new (iOS 14) DatePicker in SwiftUI, it works as expected and looks fine in the simulator & on the device, BUT as soon as the calendar pops up, I get a few HUNDRED lines of warning in the output window.  Which is a little annoying!
While the logs are posted below, the seemingly relevant content seems to be:
    UIDatePicker 0x7fbd66fc49f0 is being laid out below its minimum width of 280. This may not look like expected, especially with larger than normal font sizes.

But, as the code below shows, I'm not constraining anything narrower than 300 points.  And, everything shows up fine.
Either of two solutions would work fine from my standpoint:

*

*suppress all warnings, or

*add whatever fixes to the code to eliminate the warnings

The code that pops up the Date Picker, which generates all the warnings as soon as the control is tapped:
struct MyCustomDatePicker : View {
    var doSomething : (Date) -> ()
    @State var title: String
    @State var ignoreSelStart : Bool
    @State var ignoreSelEnd : Bool
    @State var selectedDate : Date
    @ObservedObject var limits : DateRangeLimits

    var body: some View {
        VStack {
            DatePicker(
                "\(title)", selection: $selectedDate,
                in: ((ignoreSelStart ? limits.hardStart : limits.selectedStart)...(ignoreSelEnd ? limits.hardEnd : limits.selectedEnd)), displayedComponents: [.date]
                )
            .onChange(of: selectedDate, perform: { value in
                doSomething(selectedDate)
            })
        }
        .frame(width: 400, height: 100, alignment: .center)
        .background(Color.white)
    }
}

This struct is called from here:
struct FlexChoice : View {
    @ObservedObject var limits = DateRangeLimits()

    func setStart(d: Date) {
        // stuff
    }
    func setEnd(d: Date) {
        // stuff
    }

    var body: some View {
        VStack(spacing: 0) {
            if customDateRangePossible {
                HStack {
                    MyCustomDatePicker(doSomething: self.setStart, title: "Begin ",
                                    ignoreSelStart: true, ignoreSelEnd: false,
                                    selectedDate: limits.selectedStart, limits: limits)
                    MyCustomDatePicker(doSomething: self.setEnd, title: "Finish ",
                                    ignoreSelStart: false, ignoreSelEnd: true,
                                    selectedDate: limits.selectedEnd, limits: limits)
                }       // closes HStack
            }       // closes "if customDateRangePossible..."
        }       // closes VStack
    }       // closes body
}       // closes struct

The first bit of the warnings:
2021-01-23 10:06:35.707334-0600 MyAppName[28362:46367754] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<_UISystemBaselineConstraint:0x6000011979d0 H:[_UIDatePickerLinkedLabel:0x7fbd66ffda10]-(NSLayoutAnchorConstraintSpace(8))-[UILayoutGuide:0x6000008f4540'']   (active)>",
    "<_UISystemBaselineConstraint:0x600001196f30 H:[UILayoutGuide:0x6000008f4540'']-(>=NSLayoutAnchorConstraintSpace(8))-[_UIDatePickerTouchOutsetButton:0x7fbd66f8e9d0]   (active)>",
    "<NSLayoutConstraint:0x600001197070 _UIDatePickerLinkedLabel:0x7fbd66ffda10.leading == UILayoutGuide:0x6000008f41c0'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x600001194fa0 H:[_UIDatePickerTouchOutsetButton:0x7fbd66f8e9d0]-(28)-[_UIDatePickerTouchOutsetButton:0x7fbd72922e40]   (active)>",
    "<NSLayoutConstraint:0x600001197340 _UIDatePickerTouchOutsetButton:0x7fbd72922e40.trailing == UILayoutGuide:0x6000008f41c0'UIViewLayoutMarginsGuide'.trailing   (active)>",
    "<NSLayoutConstraint:0x6000011975c0 UILayoutGuide:0x6000008f4540''.width == UIImageView:0x7fbd66f8e800.width   (active)>",
    "<NSLayoutConstraint:0x60000125fca0 _UIDatePickerCalendarContentStackView:0x7fbd66f8ad40.width <= _UIDatePickerCalendarView:0x7fbd66fc49f0.width   (active)>",
    "<NSLayoutConstraint:0x6000011c2f30 H:|-(0)-[_UIDatePickerCalendarView:0x7fbd66fc49f0]   (active, names: '|':UIDatePicker:0x7fbd7298e840 )>",
    "<NSLayoutConstraint:0x6000011c0500 _UIDatePickerCalendarView:0x7fbd66fc49f0.trailing == UIDatePicker:0x7fbd7298e840.trailing   (active)>",
    "<NSLayoutConstraint:0x60000125ee90 H:|-(8)-[UIDatePicker:0x7fbd7298e840]   (active, names: '|':UIView:0x7fbd72d46870 )>",
    "<NSLayoutConstraint:0x6000012573e0 UIDatePicker:0x7fbd7298e840.trailing == UIView:0x7fbd72d46870.trailing - 8   (active)>",
    "<NSLayoutConstraint:0x6000011de120 'UISV-canvas-connection' _UIDatePickerCalendarContentStackView:0x7fbd66f8ad40.leading == _UIDatePickerCalendarHeaderView:0x7fbd66f8aed0.leading   (active)>",
    "<NSLayoutConstraint:0x6000011df390 'UISV-canvas-connection' H:[_UIDatePickerCalendarHeaderView:0x7fbd66f8aed0]-(0)-|   (active, names: '|':_UIDatePickerCalendarContentStackView:0x7fbd66f8ad40 )>",
    "<NSLayoutConstraint:0x6000011cfca0 'UIView-Encapsulated-Layout-Width' UIView:0x7fbd72d46870.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000119cd20 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x6000008f41c0'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':_UIDatePickerCalendarHeaderView:0x7fbd66f8aed0 )>",
    "<NSLayoutConstraint:0x6000011977a0 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000008f41c0'UIViewLayoutMarginsGuide']-(8)-|(LTR)   (active, names: '|':_UIDatePickerCalendarHeaderView:0x7fbd66f8aed0 )>"
)

Will attempt to recover by breaking constraint
<_UISystemBaselineConstraint:0x600001196f30 H:[UILayoutGuide:0x6000008f4540'']-(>=NSLayoutAnchorConstraintSpace(8))-[_UIDatePickerTouchOutsetButton:0x7fbd66f8e9d0]   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

What follows are many repetitions of basically that same warning (minus the constraint that was just broken on each successive iteration).
At the very end of the hundreds of lines of warning are the following:
2021-01-23 10:06:35.734386-0600 MyAppName[28362:46367754] [DatePicker] UIDatePicker 0x7fbd66fc49f0 is being laid out below its minimum width of 280. This may not look like expected, especially with larger than normal font sizes.
2021-01-23 10:06:35.740477-0600 MyAppName[28362:46367754] [DatePicker] UIDatePicker 0x7fbd66fc49f0 is being laid out below its minimum width of 280. This may not look like expected, especially with larger than normal font sizes.
2021-01-23 10:06:35.752360-0600 MyAppName[28362:46367754] [DatePicker] UIDatePicker 0x7fbd66fc49f0 is being laid out below its minimum width of 280. This may not look like expected, especially with larger than normal font sizes.

Is there a way to make the DatePicker happy & make it so that these warnings don't flood the output window, either by fixing things or suppressing the warnings?

A: I'm getting the same warnings and I'm doing all my constraints programmatically (below).  I tried setting my constraints to lower priority (900), so that they wouldn't conflict with any system constraints that might be there but it didn't make any difference.
"V:[timePeriodControl]-(0@900)-[datePicker]"
"H:[datePicker]-(0@900)-|"

The compact picker displays the date fine at first.  It's only when I tap on the compact picker and the _UIDatePickerIOSCompactViewController is created to display the calendar that the warnings occur.  All the constraint warnings are on the calendar view, which is created by the SDK, not us.
In this screenshot from the debugger you can even see the compact date picker view is still in its right place and is the right size (blue box on right).  I checked it's constraints and they are fine (you can print out a list from the debugger).  So it's not the compact picker that's the problem, it's definitely the calendar view controller needs a radar.  This is an iOS SDK bug.

A: If you use GraphicalDatePickerStyle, try:
DatePicker("", ....)
   .datePickerStyle(GraphicalDatePickerStyle())
   .padding()  // this line solves the problem.

I use the CompactDatePickerStyle and the problem unfortunately still exists.


text:
Q: Присвоить новому столбцу значение из списка в другом столбце Имею df:
    lastUpdateId                          bids                          asks
0     1311508485   [1.66200000, 2249.05000000]   [1.66300000, 1020.40000000]
1     1311508485   [1.66100000, 4713.99000000]   [1.66400000, 6024.12000000]
2     1311508485  [1.66000000, 10568.12000000]  [1.66500000, 34493.35000000]
3     1311508485  [1.65900000, 18546.99000000]  [1.66600000, 18836.93000000]
4     1311508485  [1.65800000, 32589.85000000]   [1.66700000, 7370.94000000]

Как присвоить новому столбцу, к примеру 'b_p', значение из списка столбца 'bids'? Чтобы получилось:
    lastUpdateId                          bids                          asks         b_p
0     1311508485   [1.66200000, 2249.05000000]   [1.66300000, 1020.40000000]  1.66200000
1     1311508485   [1.66100000, 4713.99000000]   [1.66400000, 6024.12000000]  1.66200000
2     1311508485  [1.66000000, 10568.12000000]  [1.66500000, 34493.35000000]  1.66200000
3     1311508485  [1.65900000, 18546.99000000]  [1.66600000, 18836.93000000]  1.66200000
4     1311508485  [1.65800000, 32589.85000000]   [1.66700000, 7370.94000000]  1.66200000

Реализовал через цикл:
for i in range(len(a['lastUpdateId'].tolist())):
   a.loc[i, 'b_p'] = float(a.bids[i][0])

Но мне кажется можно реализовать это быстрее:)
Заранее спасибо!

A: не просто можно, а нужно. к спискам в значениях можно обратиться через модификатор str:
df["b_p"] = df["bids"].str[0]
print(df)

   lastUpdateId               bids               asks    b_p
0    1311508485   [1.662, 2249.05]    [1.663, 1020.4]  1.662
1    1311508485   [1.661, 4713.99]   [1.664, 6024.12]  1.661
2    1311508485   [1.66, 10568.12]  [1.665, 34493.35]  1.660
3    1311508485  [1.659, 18546.99]  [1.666, 18836.93]  1.659
4    1311508485  [1.658, 32589.85]   [1.667, 7370.94]  1.658

Ну и тип данных остался таким, какой нужен:
print(df.info())

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
 #   Column        Non-Null Count  Dtype
---  ------        --------------  -----
 0   lastUpdateId  5 non-null      int64
 1   bids          5 non-null      object
 2   asks          5 non-null      object
 3   b_p           5 non-null      float64
dtypes: float64(1), int64(1), object(2)


text:
Q: 4K screen set to 1920x1080 but still locked at 30Hz I recently bought a 4K screen but my graphic card (Nvidia Geforce 710 GT) is not able to properly display a 4K-60Hz, so for the moment would like to set the screen resolution to 1920x1080 in order to come back to 60Hz refresh rate.
The problem is that I am still locked at 30Hz and even if the option seems to be possible, I get an error message while trying to set the refresh rate to 60Hz:
https://i.imgur.com/oeEsNhB.png
I tried to reinstall my drivers but nothing changed.


text:
Q: How to execute a constructor more than once without page refresh I am new in using OOP methodology in javascript, I use the following code below as a constructor.
var post = function post() {}

I call the constructor inside a jQuery event handler
post = new post();

At first run or on each page refresh, it works well because a method invocation after calling the constructor gets executed. But on clicking the button that triggers the event the second time, it would not execute anymore, I instead get the following error message in firebug
TypeError: post is not a constructor

So why does it not work again after the first run, without a page refresh?
And how will I make it work continuously without page refresh?

A:
So why does it not work again after the first run

Because you've overwritten the post symbol. This line:
post = new post();

Calls your post constructor and assigns the resulting object to the post variable. Now post isn't a constructor function anymore, it's the object created via new post.
Just use a different name:
var p = new post();

Side note: The overwhelming convention in JavaScript is that constructor functions start with an initial upper case letter, e.g. Post rather than post. You're free to ignore that convention, but it may make it difficult for others to read your code (for instance, here on SO).


text:
Q: Count occurencies of value from csv column in other file/s and append as a new column can I make this work with basic shell tools(no Python or Perl)?
INPUT1:
file1.csv
    John,Doe,john@mail.com
    Andy,Barry,barry@mail.com
    Mary,,mary@yahoo.com

count occurencies of emails from 3rd column,file1 in
INPUT2:
file2.log
    mary@yahoo.com&fghfgh
    asdda&barry@mail.com
    barry@mail.com&werewr

desired
OUTPUT:
result.csv
    John,Doe,john@mail.com,0
    Andy,Barry,barry@mail.com,2
    Mary,,mary@yahoo.com,1

many thanx!

A: You didn't provide valid input, so I used this:
John,Doe,barry@mail.com
Andy,Barry,barry@mail.com
Mary,,mary@yahoo.com

For which the following awk one-liner gives expected results:
awk -F, '{l[NR]=$0;f[NR]=$3;c[$3]++}END{for(i=1;i<=NR;i++)print l[i] "," c[f[i]]}'

The issue here is that your task requires either two passes.  (f[] is just a convenience to avoid keeping the entire content parsed, or re-parsing it at the end.)  But since I don't understand why you ruled out python or perl (they are basic shell tools), perhaps you don't consider awk fair game either...


text:
Q: ModelAndViewDefiningException при вызове рест-методов? Приложение на spring 4.3.13.RELEASE версии и все модули, например mvc или web используют внутри себя servlet 3.0.1
Приложение задеплоено на websphere 8.5.5.13, на котором встроенный jar servlet 3.0
Работает все ок, но после перезагрузки приложения, при попытке повызывать ресты, получаю
Error 500: org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/springframework/web/servlet/ModelAndViewDefiningException
pom.xml файл выглядит так
...
    war
<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>4.3.13.RELEASE</spring.version>
    <javax.servlet>3.0.1</javax.servlet>
    <hb.enity.manager>4.2.21.Final</hb.enity.manager>
    <spring.test>3.2.4.RELEASE</spring.test>
    <junit.version>4.11</junit.version>
    <slf4j.version>1.7.25</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
</properties>

<build>
    <finalName>SBRiskDataSvcs</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    <testResources>
        <testResource>
            <directory>src/test/resources</directory>
        </testResource>
    </testResources>
    <testSourceDirectory>src/test</testSourceDirectory>
</build>

<dependencies>
    <!--SPRING-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
        <version>1.11.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
    <!-- SERVLET-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>${javax.servlet}</version>
        <scope>provided</scope>
    </dependency>
    <!--JACKSON AND XML-->
    <dependency>
        <groupId>javax.xml.bind</groupId>
        <artifactId>jaxb-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <!--DATABASE-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-envers</artifactId>
        <version>4.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>com.oracle.odb</groupId>
        <artifactId>ojdbc7</artifactId>
        <version>12.1.0.2.0</version>
    </dependency>
    <!--APACHE-->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.8.1</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
    </dependency>
    <!--TEST-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!--LOG4J-->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.25</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-over-slf4j</artifactId>
        <version>1.7.25</version>
    </dependency>
</dependencies>

Полный код ошибки

00000096 ServletWrappe E
  com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0014E:
  Uncaught service() exception root cause dispatcher:
  org.springframework.web.util.NestedServletException: Handler
  processing failed; nested exception is java.lang.NoClassDefFoundError:
  org.springframework.web.servlet.ModelAndViewDefiningException at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:990)
  at
  org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
  at
  org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
  at
  org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:595) at
  org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
  at javax.servlet.http.HttpServlet.service(HttpServlet.java:668) at
  com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
  at
  com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
  at
  com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
  at
  com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
  at
  com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
  at
  com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:97)
  at
  org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
  at
  org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
  at
  com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:195)
  at
  com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:91)
  at
  com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:967)
  at
  com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1107)
  at
  com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:4028)
  at
  com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
  at
  com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:1016)
  at
  com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
  at
  com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
  at
  com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
  at
  com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
  at
  com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
  at
  com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
  at
  com.ibm.ws.ssl.channel.impl.SSLConnectionLink.determineNextChannel(SSLConnectionLink.java:1187)
  at
  com.ibm.ws.ssl.channel.impl.SSLConnectionLink$MyReadCompletedCallback.complete(SSLConnectionLink.java:694)
  at
  com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
  at
  com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
  at
  com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
  at
  com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
  at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138) at
  com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204) at
  com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
  at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905) at
  com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892) Caused by:
  java.lang.NoClassDefFoundError:
  org.springframework.web.servlet.ModelAndViewDefiningException at
  org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1028)
  at
  org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:984)
  ... 38 more Caused by: java.lang.ClassNotFoundException:
  org.springframework.web.servlet.ModelAndViewDefiningException at
  java.net.URLClassLoader.findClass(URLClassLoader.java:609) at
  com.ibm.ws.bootstrap.ExtClassLoader.findClass(ExtClassLoader.java:243)
  at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:924) at
  java.lang.ClassLoader.loadClass(ClassLoader.java:869) at
  com.ibm.ws.bootstrap.ExtClassLoader.loadClass(ExtClassLoader.java:134)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:852) at
  com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:62)
  at
  com.ibm.ws.classloader.ProtectionClassLoader.loadClass(ProtectionClassLoader.java:58)
  at
  com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:852) at
  com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:852) ... 40 more

Есть подозрения, что после перезагрузки classLoader читает servlet 3.0 jar файл вместо того чтобы читать servlet 3.0.1
Какое решение может быть у этой проблемы?
Понижение версии спринга до 3 версии?


text:
Q: Add a grid column showing values I've added some fields in a form using an array as source:
 $addInternalInformation->addField(
        'return_type', 'select',
        array(
            'name'  => 'return_type',
            'label' => $this->__('Return type'),
            'values' => Mage::getModel('modulename/source_returntype')->toOptionArray()
        )
    );

Now I'd like to show that values in the grid instead of the index, should I use a Render Class or there is a simpler method?
Thanks

A: I solved creating a _toOption() function to use inside the addColumn grid method:
$this->addColumn(
            'return_type',
            array(
                'header'  => 'return_type',
                'index' => 'return_type',
                'type' => 'options',
                'options' => $this->_toOptions(Mage::getModel('modulename/source_returntype')->toOptionArray())

            )
        );

protected function _toOptions($optArray){
        $options=array();
        foreach ($optArray as $option){
            $options[$option['value']] = $option['label'];

    }


text:
Q: Cómo utilizar != (diferente) con un array? Tengo que traer el resultado de una consulta, me explico mejor, los usuarios tienen asignados proyectos, pero se pueden postular en otros, Pero... como puedo hacer para que, en la vista de postulación, NO se le muestren los proyectos que ya tiene asignados?. Sé que con el operador !=, lo puedo hacer, pero que yo sepa solo se haría la validación de un registro solamente, pero como puedo hacer para que se valide si tiene más de un proyecto asignado? Espero darme a entender.. Gracias
Esta es mi relación entre proyecto y usuarios

Mi consulta queda dada:
select p.idproyecto, p.nombreProyecto, p.descripcion
from `proyecto` p
where p.idproyecto != 1

donde se mostrarán los demás proyectos, en donde el usuario no está asignado, pero digamos que la clausula where quede where p.idproyecto <> 1 and  p.idproyecto <> 7 o <>12
Dependiendo de los proyectos que tenga el usuario, que muestre los que no tiene
Trabajo con PHP y mysql
Creo que primeramente tendría que consultar los proyectos donde el usuario está y después devolver los que no tiene, si estaría bien?

A: De inicio, el operaror <> es el estándar ANSI SQL para indicar diferente de. Pero en este caso, requieres usar NOT IN:
Para mostrar los proyectos en los cuales no está asignado:
SELECT
    *
FROM proyecto
WHERE idproyecto NOT IN (
    SELECT
        P.idproyecto
    FROM proyecto P
        INNER JOIN proyecto_usuarios PU
            ON P.idproyecto = PU.proyecto_idproyecto
        INNER JOIN usuarios U
            ON PU.usuarios_idusuarios = U.idusuarios
    WHERE U.idusuarios = --aquí va el id del usuario a buscar
)

A: Podrias utilizar un ciclo while:
$conexion = mysqli_connect($server, $user, $pass, $bd) or die("Ha sucedido un error.");
$sql = "SELECT * FROM proyectos INNER JOIN proyecto_usuarios ON proyectos.idproyecto != proyecto_usuarios.proyecto_idproyecto";

mysqli_set_charset($conexion, "utf8");

if(!$result = mysqli_query($conexion, $sql)) die ("Se ha generado un error.");

while($row = mysqli_fetch_array($result)) {
    $data = $row['idproyecto'];
    $data1 = $row['nombreProyecto'];
}


text:
Q: How to only utilise certain class of the element based on its parent class without using JavaSctript? I am trying to do the following: when div container has the class show, the span will only use class pseudo2 otherwise will use class pseudo1. There is a predefined css file that I don't want to modify, and I have pasted my custom css file, however it doesn't seem to work. Anyone know better solution?
html

predefined css
.pseudo1:before{
   content:"/012";
}
.pseudo2:before{
   content:"/013";
}

my custom css
.show .pseudo1:before{
   content:none;
}
.show .pseudo2:before{
   content:"/013";
}
.pseudo2:before{
       content:none;
}

A: The CSS cascading order is very important:
.show .pseudo2:before{
   content:"/013";
}
.show .pseudo1:before{
   content:none;
}

Now, .show .pseudo1:before is more relevant. Also you can use the !important.
See how works: http://jsfiddle.net/btj62bfv/1/.
Read about this in the W3 webpage.

A: You don´t need the content:none; to get this done, see the DEMO:
Your predefined css file that you don't want to modify
.pseudo1:before{
   content:"/012";
}
.pseudo2:before{
   content:"/013";
}

Your custom css
.pseudo1:before{
   content:"/012";
}

.show .pseudo2:before{
   content:"/013";
}

A: I think using the classes .pseudo1 and .pseudo2 is a bit confusing, so I did something simplier :
/* predefined css */

.pseudo1:before{
   content:"/012";

}
.pseudo2:before{
   content:"/013";
}

/* my custom css */

.container span:before{
   content:"/012";
}
.container.show span:before{
   content:"/013";
}

It's basically overriding the predefined rules, but IMHO it's easier to read.
http://jsfiddle.net/Lado0kmp/1/


text:
Q: Change email subjects for some specific email notifications in Woocommerce I would like to standardize structure of email subjects (for all Woocommerce emails notifications).
Im using all available filters from here
But what about "On hold", "Cancelled", "Refunded" and "Failed order" email subjects?
Is there way to change email subject for those emails?

A: Below the 4 hooked functions with the correct filter hooks, that will allow you to customize the email subjects for "On hold", "Cancelled", "Refunded" and "Failed order" notifications:
add_filter( 'woocommerce_email_subject_customer_on_hold_order', 'customizing_on_hold_email_subject', 10, 2 );
function customizing_on_hold_email_subject( $formated_subject, $order ){
    return __("This is the custom on hold order email notification subject", "woocommerce");
}

add_filter( 'woocommerce_email_subject_cancelled_order', 'customizing_cancelled_email_subject', 10, 2 );
function customizing_cancelled_email_subject( $formated_subject, $order ){
    return __("This is the custom on cancelled email notification subject", "woocommerce");
}

add_filter( 'woocommerce_email_subject_customer_refunded_order', 'customizing_refunded_email_subject', 10, 2 );
function customizing_refunded_email_subject( $formated_subject, $order ){
    return __("This is the custom on refunded email notification subject", "woocommerce");
}

add_filter( 'woocommerce_email_subject_failed_order', 'customizing_failed_email_subject', 10, 2 );
function customizing_failed_email_subject( $formated_subject, $order ){
    return __("This is the custom on failed email notification subject", "woocommerce");
}

Code goes in function.php file of the active child theme (or active theme).
Tested and works.

You can use the WC_Order object argument $order to customize the subjects with dynamic order data…
Like for Example (with dynamic order ID and order formatted date modified):
add_filter( 'woocommerce_email_subject_cancelled_order', 'customizing_cancelled_email_subject', 10, 2 );
function customizing_cancelled_email_subject( $formated_subject, $order ){
    $modified = $order->get_date_modified(); // Get date modified WC_DateTime object
    return sprintf( __('Order #%d  was cancelled on %s', 'woocommerce'), $order->get_id(), $modified->date_i18n( 'l jS \of F Y \a\t h:i:s A' ) );
}

related: Change email subject for custom order statuses in Woocommerce 3


text:
Q: Calculate difference between date times in typescript angular I have my two string values startTime that is written in format: 14/03/2022, 17:12:19
and stopTime that is written in format: 14/03/2022, 17:15:19 and I need to get difference between these two times in angular typescript file I need to get 03:00 as my answer.
This is what I tried but getTime() method seem to not exist in typescript:
  calculateDuration(startTime:string,stopTime:string)
  {
    this.myStartDate = new Date(startTime);
    this.myEndDate = new Date(stopTime);
    this.diff = this.myEndDate.getTime() - this.myStartDate.getTime();
    console.log(this.diff);
  }

I also tried parsing with:
  calculateDuration(startTime:string,stopTime:string)
  {
    this.myStartDate = Date.parse(startTime)
    this.myEndDate = Date.parse(stopTime);
    this.diff = this.myEndDate - this.myStartDate;
    console.log(this.diff);
  }

But this only prints Nan
This is my html file:

Timely Application

    <app-table-form></app-table-form>

                Project Name
                Start Time
                Stop Time
                Duration

                {{tf.projectName}}
                {{tf.startTime}}
                {{tf.stopTime}}
                {{tf.duration}}

                    <button style="margin-left: 40px;" (click)="(calculateDuration(tf.startTime,tf.stopTime))">Calculate duration</button>

Any suggestions?

A: You can try something like this:
this.getDifference(this.startTime, this.stopTime); // use your vars' names

  getDifference(start: string, stop: string) {
    // getting startTime timestamp:
    let startTimestamp = this.getTimestamp(start);
    // getting stopTime timestamp:
    let stopTimestamp = this.getTimestamp(stop);
    // getting the difference in various formats:
    // hh:mm:ss
    let differenceInSecs = stopTimestamp - startTimestamp;
    let inHhMmSsFormat = new Date(differenceInSecs * 1000)
      .toISOString()
      .slice(11, 19);
    console.log('Difference in hh:mm:ss format: ', inHhMmSsFormat);
    // mm:ss
    let inMmSsFormat = new Date(differenceInSecs * 1000)
      .toISOString()
      .slice(14, 19);
    console.log('Difference in mm:ss format: ', inMmSsFormat);
  }

  getTimestamp(time: string) {
    let timeFirst = time.split(', ')[0].split('/');
    let timeY = timeFirst[2];
    let timeM = timeFirst[1];
    let timeD = timeFirst[0];
    let timeSecond = time.split(', ')[1];
    let timestamp =
      new Date(
        Date.parse(
          timeY + '-' + timeM + '-' + timeD + ' ' + timeSecond + '+0000'
        )
      ).getTime() / 1000;
    return timestamp;
  }

Stackblitz: https://stackblitz.com/edit/angular-wk2fet

A: this.myStartDate = new Date(startTime);

Using the above line to create a Date can't work, because it requires a number as an argument, not a string.
But if that's the only string format you can use, here I've prepared a short solution for you:
const startDate: string = '14/03/2022, 17:12:19';
const endDate: string = '14/03/2022, 17:15:19';

const calculateDuration = (startTime:string, stopTime:string) => {

 const lPartSplittedStartDate: string[] = startTime.split('/');
 const rPartStartDate: string[] = lPartSplittedStartDate[2].split(',');
 const rPartSplittedStartDate: string[] = rPartStartDate[1].split(':');

 const myStartDate: Date = new Date(
    parseInt(lPartSplittedStartDate[2]),
    parseInt(lPartSplittedStartDate[1]),
    parseInt(lPartSplittedStartDate[0]),
    parseInt(rPartSplittedStartDate[0]),
    parseInt(rPartSplittedStartDate[1]),
    parseInt(rPartSplittedStartDate[2])
 );

 const startTimestamp: number = myStartDate.getTime();

 const lPartSplittedEndDate: string[] = stopTime.split('/');
 const rPartEndDate: string[] = lPartSplittedEndDate[2].split(',');
 const rPartSplittedEndDate: string[] = rPartEndDate[1].split(':');

 const myEndDate: Date = new Date(
    parseInt(lPartSplittedEndDate[2]),
    parseInt(lPartSplittedEndDate[1]),
    parseInt(lPartSplittedEndDate[0]),
    parseInt(rPartSplittedEndDate[0]),
    parseInt(rPartSplittedEndDate[1]),
    parseInt(rPartSplittedEndDate[2])
 );

 const endTimestamp: number = myEndDate.getTime();

 const newNumber: number = endTimestamp - startTimestamp;
 const diffMinutes: number = Math.ceil(newNumber / (1000 * 60));

 console.log(diffMinutes)

 return diffMinutes;
}

calculateDuration(startDate, endDate);


text:
Q: How to get around PowerCLI Connect-VIServer I am pretty new to using PowerCLI and I would like to use it to automate a couple of things, but it does not seem to allow me to run what I want to without connecting to a server. I do not want to have to connect to a server to automate the service I am trying to run. Would anyone have any ideas on how to work around the Connect-VIServer issue?
If it helps I am trying to use the Set-Template command to convert my file to a VM.
Any help would be much appreciated! Thanks!

A: If you don't own a copy of vCenter you can still get a lot out of PowerCLI.
PowerCLI will enable you to manage multiple ESX servers at once even without vCenter,
but no *vMotion or templates*, you still need vCenter for those features!
So you can't avoid the use of connect-viserver


text:
Q: Прямая ссылка на видео youtube Столкнулся с проблемой прямой ссылки на видео YouTube. Хочу, что бы при вводе в поле ссылки на YouTube, само видео скачивалось на сервер. Буду признателен, если расскажете, как это сделать со всеми мелочами. Заранее спасибо.
Видео по ссылкам, которые выходят, не открывается:
<?php
    $data = file_get_contents("https://www.youtube.com/get_video_info?video_id=030YR0Fwb4s");
    parse_str($data);
    $arr = explode(",", $url_encoded_fmt_stream_map);
    foreach ($arr as $item) {
        parse_str($item, $vdata);
        print_r($vdata);
    }
?>

A: Этот вопрос подробно раскрыт в статье на habrahabr.ru.
Насколько показали мои простые опыты в браузерном JS с двумя разными видео-роликами с youtube - если что-то и изменилось с момента написания статьи, то незначительно. Бегло ознакомившись с ней я попробовал следующее:
Нашел свежий ролик, загруженный 26.06.2016: https://www.youtube.com/watch?v=iI0Sw4eS1TE
Использовав id видео из ссылки открыл адрес https://www.youtube.com/get_video_info?video_id=iI0Sw4eS1TE
и скачал файл, содержащий длинную строку данных. Далее, перешел в редактор javascript и накидал следующий код:
//исходная строка
var str = 'содержимое загруженного файла';
//функция для создания уникальных ключей. дальше рассказано зачем.
var genKey = function(key, arr){
    if(arr[key]){
        key = key+1;
        return genKey(key, arr);
    } else {
        return key;
    }
}
//из строки запроса делает ассоциативный массив.
var parseQuery = function(s){
    var t = s.split('&');
    var query = {};
    for(var k in t){
        var t2 = t[k].split('=');
        //выяснилось, что в данных под url_encoded_fmt_stream_map ключи повторяются (url=*&url=*&url=*). Чтобы избежать перезаписи ключей применил простейшую функцию genKey.
        var key = genKey(t2[0], query);
        query[key] = t2[1];
    }
    return query;
};

//получаем массив данных раскодируя исходную строку
var tmp = parseQuery(str);
//под ключом url_encoded_fmt_stream_map находим интересующий нас список урлов. он в urlencoded-виде.
var encodedStreamMap = tmp['url_encoded_fmt_stream_map'];
//превращаем с массив данные из url_encoded_fmt_stream_map, предварительно сделав urldecode строки.
var stream_map = parseQuery(decodeURIComponent(encodedStreamMap));

//под ключом "url" в массиве находится ссылка на самое качественное видео (по моим двум экспериментам, по крайней мере)
var url = decodeURIComponent(stream_map['url']);

"живые" данные не добавил, т.к. они слишком объемные и содержат мои идентификаторы, лучше используйте свои.
В переменной url, в итоге, оказывается ссылка на видео, при открытии которой в браузере сразу начинается скачивание.
Естественно, я не призываю писать все этой на JS (хотя, почему бы и не node.js), я лишь демонстрирую действия, при которых у меня все получилось. Код можно переписать на PHP или что-то другое.
Возможно, итоговая ссылка не захочет открываться на других машинах, но автор статьи на habrahabr говорит об этом и дает рекомендации, как поступить в этом случае. А именно - удалить из url все идентификационные данные. По мнению автора, это "все параметры после id". Конкретно в моем случае это следующие ключи (пригодится, если порядок изменится):
upn,ip,key,mv,mt,ms,ipbits,initcwndbps,cnr,signature,sver,ratebypass


text:
Q: jQuery calling post URL    $.post('controller/method', $("#form").serialize , function(data) {
       //alert data
   });

It works if domain name is www.domain.com
It doesn't work if domain name is domain.com/category/
What should I do here? Or I must use PHP to help me? Thanks.

A: If you have to support both domains, try switching to JSONP instead of a traditional ajax call.  This will work with multiple domains, but it is limited to GET requests.  So, if your php code will work with the parameters passed in the URL, this should be fine.
$.ajax({
  url: 'controller/method',
  data: $("#form").serialize(),
  dataType: 'jsonp',
  success: function(data) {
       //alert(data);
   }
});

In addition to the fact that the PHP code will have to work with GET requests, it will also have to respond with JSON.  Also, that JSON will have to be wrapped in call to invoke the $callback function, like so:
<%= echo %callback . '(' . $jsonResponse . ')' %>

See more about JSONP here:  http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/


text:
Q: Antenna requirements, transmit vs. receive This question is an extension of this question: Are antennas specified for a certain frequency?
I've heard that receive requirements for antennas are much more lax than transmit requirements.  From what I understand transmit antennas should relatively efficiently radiate frequencies within the transmit bandwidth, or there is risk of reflection and potentially equipment damage (in addition to the problem of inefficiently radiating).
Requirements for receive antennas are much less strict.  An antenna can receive signals outside of its specified (tuned / transmit) range, and even efficiently, presumably barring extremes (very long antennas for UHF signals for example)
Is my understanding correct?

A: For efficiently transfer RF energy to/from a circuit, you want an antenna that's impedance is matched to the circuit.  But what happens if they are not matched?
RX
For the RX case, you will get poor energy reception. And thus poor signal strength.

TX
For the TX case, due to reciprocity, you'll also have poor energy transfer out of the circuit to the antenna.

However, there is an additional consideration for TX, and that is reflections.
When the antenna isn't matched to the circuit there will be some form of a standing wave on the transmission line (between the output amplifier and the antenna).  When that standing wave gets to be too large due to mismatch, then it can damage the amplifier.  A standard way to measure this is called the Standing Wave Ratio (SWR).
When the output power is low (eg. 100mW) then the transistors used in the output amplifier are much more easily able to withstand a large SWR value (large SWR is greater than 2.0) as the voltages are not that great.  However, when you start increasing the output power, then the voltages increase, and the transistors can be damaged if the SWR is too high (ie. antenna is mismatched to the amp).

A: *

*Every antenna either Tx or Rx has gain for direction "aka" ( Also Known As ) diversity.  Thus the smaller the beam angle, the greater the focus gain possible.

*Then there are losses for mismatch on impedance vs frequency such as 1/4 wave "pole "(or element or whip) or 1/2 dipole wavelength or feedpoint into a patch resonant dielectric conductor.

*gain of the antenna is relative to a theoretical spherical antenna called isotropic gain. [dBi]

*Since a spherical antenna is not often desired, (or even possible) some minor gains and
conduction losses are measured for directional antenna to give the
net results. E.g a perfect half sphere would have a gain of 3 dBi.

*damage occurs when a high power Tx is unprotected against open or short circuit conditions.
Other info
Ideally BW of Tx and Rx are matched to the spectral BW down to less than -40 dB.  The ability of the Rx depends on the Carrier to Noise Interference ratio or CNR of the Demodulator and if excessive BW or poor CNR from strong interference, then either tuning the 1st stage filter or aiming away from the interference can improve the CNR.
If conversion is used to an IF, you are still dealing with CNR gains from the BW of the IF blocking interfering channel noise.  after demodulation to the baseband signals then it is called SNR.
for example in 2.4G and 5G modems the 1st  indicator is the received signal strength indicator or RSSI and on all mobiles is calibrated from the AGC voltage into dBm where the maximum bit rates e.g. 834 Mbps (? Check) on high speed WiFi,  need much higher RSSI levels (10 to 20 dB) to maintain the BER at this higher SNR than the lower 11 Mbps rates according to Hartley's Laws relating Bit/Baud and the log of signal level [dB]  Then Shannon's Law expanded on this to generalize the error probability.  RSSI in dBm is only available with 3rd party apps, otherwise all you have 3 bars max and less than this implies lower max data rate limits.
So with forward error correction [FEC] almost error free reception above -75 dBm is adequate for 11 To 54 Mbps and to go 10x faster requires at least 10 db more signal.  Multi-path interference will increase the error rates and thus reduce the SNR accordingly and may be extremely sensitive to 1mm displacement or 1 deg aiming of weak signals when in a deadspot from these Rician Fading losses.
https://en.wikipedia.org/wiki/Shannon%E2%80%93Hartley_theorem


text:
Q: Why is it "play" instead of "plays" in "What we're seeing *play out* there are..."? I'm having trouble understanding the grammatical structure of the two sentences below.
Shouldn't it be "plays out" instead of "play out" in both of these sentences, since the subject is "what"? As in, "what is playing out(what is happening now) in Ukraine..."

"In the context of the horrors of what we're seeing play out in Ukraine, the day to day running of a football club pales into insignificance."

"What we're seeing play out there are the somewhat toxic politics of national security, which have swamped countries around the West since 9/11,"

What have I got wrong?

A: It's exactly the same construction as this:

*

*He walks.

*I see him walk.

The "walk" is the infinitive, which is following our main verb. An example that makes clear that it's the infinitive is:

*

*She is silly.

*I saw her be silly.

So:

*

*What plays out in Ukraine...

*What we're seeing play out in Ukraine...

A: "In the context of the horrors of what we're seeing play out in Ukraine, the day to day running of a football club pales into insignificance."
we're seeing is followed by a bare form of the verb play out.
Compare:
"In the context of the horrors of what is playing out in Ukraine, the day to day running of a football club pales into insignificance."
That would be third person continuous. And of course, present simple here does not work as present simple is for general statements.

A:
In the context of the horrors of [what we're seeing play out in
Ukraine], the day to day running of a football club pales into*
insignificance.

[What we're seeing play out there] are the somewhat toxic politics of
national security, which have swamped countries around the West since
9/11.

In both examples, the bracketed element is a noun phrase in a 'fused' relative construction where the word "what" (meaning "that which") is simultaneously head of noun phrase and subject of the embedded "play" clause. "See" is a catenative verb here that  requires as its complement either an infinitival clause with the plain form verb "play" or a gerund-participial clause with the gerund-participial verb "playing". The author chose the former.