text:
Q: Remove duplicates from result set using javax.persistence.criteria by data prorety I need to return the latest data. Date fields are called dateModified. Since the old data is not deleted in any way, there are a lot of similar records, they differ only in the dateModified field. The current query returns all records, and I need only the most recent in the field dateModified.
    public List<SomeDto> search(SearchDto criteria) {
            final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            final CriteriaQuery<SomeDto> query = cb.createQuery(SomeDto.class);
            final Root<SomeModel> root = query.from(SomeModel.class);
            query.multiselect(
                 root.get(ID),
                 root.get(SOME_ENTERNAL_ID),
                 root.get(SOME_NAME_ID));
                 query.where(createPredicates(cb, query, root, criteria));
    return entityManager.createQuery(query).getResultList();
}

A: Try to order all the results in descending order and get the first result, something like this:
public List<SomeDto> search(SearchDto criteria) {
            final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            final CriteriaQuery<SomeDto> query = cb.createQuery(SomeDto.class);
            final Root<SomeModel> root = query.from(SomeModel.class);
            query.multiselect(
                 root.get(ID),
                 root.get(SOME_ENTERNAL_ID),
                 root.get(SOME_NAME_ID));
                 query.where(createPredicates(cb, query, root, criteria))
                      .orderBy(cb.desc(root.get("dateModified")));
    return entityManager.createQuery(query)
                        .setFirstResult(0)
                        .setMaxResults(1)
                        .getResultList();
}

The method will return a list with one element which has the most recent dateModified.


text:
Q: Nesting/grouping a range of columns when converting a Pandas DataFrame to a dictionary I've been trying to work out how to convert a Pandas DataFrame into a list of nested dictionaries and I haven't been having any luck.
My first thought was to convert the DataFrame into a list of dictionaries (with users = users.to_dict(orient='records')) and then merge the 'address' and 'color_preference' items into sublists but there must be a better way to do it!
I have a dataframe like this:
import pandas as pd
users = pd.DataFrame({'email_address': ["email@email.com"], 'status': ["active"], 'address': ["1 Eagle St"],  'suburb': ["BROOKLYN"],  'state': ["NY"],  'postcode': ["11201"],  'country': ["USA"],  'red': [False],  'orange': [True],  'yellow': [True],  'green': [True],  'blue': [False],  'indigo': [False],  'violet': [False]})

and I'm trying to convert it into this format:
{
   "email_address":"email@email.com",
   "status":"active",
   "address":{
      "address":"1 Eagle St",
      "suburb":"Brooklyn",
      "state":"NY",
      "postcode":"11201",
      "country":"USA"
   },
   "color_preference":{
      "red":false,
      "orange":true,
      "yellow":true,
      "green":true,
      "blue":false,
      "indigo":false,
      "violet":false
   }
}

A: You can do this explicitly with apply (I've done the first couple but you could do all the address/colors):
def extract_json(row):
  return {
    "email_address": row.loc["email_address"],
    "status": row.loc["status"],
    "address": row.loc[["address", "suburb"]].to_dict(),
    "color_preference": row.loc[["red", "orange"]].to_dict()
  }

In [11]: users.apply(extract_json, axis=1)
Out[11]:
0    {'email_address': 'email@email.com', 'status':...
dtype: object

In [12]: users.apply(extract_json, axis=1).tolist()
Out[12]:
[{'email_address': 'email@email.com',
  'status': 'active',
  'address': {'address': '1 Eagle St', 'suburb': 'BROOKLYN'},
  'color_preference': {'red': False, 'orange': True}}]

You could pull out all the address/colors by position:
In [21]: users.columns[2:7]
Out[21]: Index(['address', 'suburb', 'state', 'postcode', 'country'], dtype='object')

In [22]: users.columns[7:]
Out[22]: Index(['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'], dtype='object')

redpajama_set_name: RedPajamaStackExchange


text:
Q: What IAM Policies control Firebase Function Configs I would like to manage which of my developers has access to firebase configs, or at the very least not allow them to edit them:
https://firebase.google.com/docs/functions/config-env
I can't find documentation on which policy controls it (I found firebase remote config but it's something different).
What is the IAM policy for controlling whether someone can access the firebase config? Or the ability to edit them?
Also, is there a UI where I can see where the configs are in GCP / Firebase console? I only see commandline options firebase functions:config:get.

A: The Cloud Functions for Firebase functions.config() is powered by Cloud Runtime Configurator under the covers. The permissions that you'll need are listed in the documentation. Read/write access to both configs and variables is necessary to manage functions.config().
Unfortunately there are no curated roles available for Runtime Conifgurator, but the permissions are included in the Firebase Develop Admin role.


text:
Q: Presenting an Interstitial Ad in a Game Over Scene linking to GameViewController? I've integrated a banner view into a scene within my application however I'm failing to integrate a Interstitial ad within another scene.
Here is my code:
import SpriteKit
import GameKit
import GoogleMobileAds
 class GameOverMenu: SKScene, GKGameCenterControllerDelegate,    UIAlertViewDelegate {

var viewController: GameViewController!
var interstitial: GADInterstitial!

var myTimer = Timer()

override func didMove(to view: SKView) {

 createAndLoadInterstitial()

startMyTimer()

}

func createAndLoadInterstitial() {
interstitial = GADInterstitial(adUnitID: "...")
let request = GADRequest()
request.testDevices = [ kGADSimulatorID, "..." ]
interstitial.load(request)
}

func startMyTimer() {
myTimer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(GameOverMenu.myFunction), userInfo: nil, repeats: false)

}

func myFunction(){

if interstitial.isReady {
    interstitial.present(fromRootViewController: viewController)
} else {
    print("Ad wasn't ready")
}

 }

It is failing when it tries to load with "fatal error: unexpectedly found nil while unwrapping an Optional value". The problem lies below as if the code is displayed like this and I load the GameOver scene when the application launches it works fine. How can I fix this?
if let view = self.view as! SKView? {

    // Load the SKScene from 'MainMenu.sks'
    if let scene = MainMenuScene(fileNamed: "MainMenu") {

        scene.viewController = self

        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill

        // Present the scene
        view.presentScene(scene)

    }

    if let scene3 = GameOverMenu(fileNamed: "GameOver") {

        scene3.viewController = self

        // Set the scale mode to scale to fit the window
        scene3.scaleMode = .aspectFill

        view.presentScene(scene3)

    }

A: The problem is that when you transition between 2 scenes you loose the reference to GameViewController e.g
 scene3.viewController = self

thats why it only works when you launch the application.
You are also using ! on those properties
 var viewController: GameViewController!
 var interstitial: GADInterstitial!

so if they are nil you will crash. So you should alway use ? when you are not 100% sure that something is there.
 var viewController: GameViewController?
 var interstitial: GADInterstitial?

and than in your code such as "myFunction" you will use the "?" and "if let" to not crash when the properties are nil.
  if let ad = interstitial, let vc = viewController, ad.isReady {
       ad.present(fromRootViewController: vc)
   } else {
       print("Ad wasn't ready")
   }

The general fix for your problem is that you should really move all your AdMob code directly into GameViewController. Than you can use something like NotificationCenter or delegation to forward a message from your scenes to your ViewController to show the ad. Its not really the best practice to reference your ViewController in your SKScenes.
So move all the ad code to your ViewController and than in GameViewController outside the class implementation create this extension for the notification key
 extension Notification.Name {
       static let showAd = Notification.Name(rawValue: "NotificationShowAd")
 }

  class GameViewController: UIViewController {...

Than in GameViewController in ViewDidLoad you can add the observer
override func viewDidLoad() {
    super.viewDidLoad()

         createAndLoadInterstitial()

         NotificationCenter.default.addObserver(self, selector: #selector(myFunction), name: .showAd, object: nil)

         ....
 }

Now whenever you need to show an ad from any of your SKScenes you can call this
NotificationCenter.default.post(name: .showAd, object: nil)

To make your life even easier have a look at my helper on GitHub
https://github.com/crashoverride777/SwiftyAds
hope this helps


text:
Q: Connect to remote dbf file with lazarus on linux I need migrate a windows application made with delphi xe3 to a linux platform using Lazarus.
This application connect to dbf files hosted on a windows server 2008.
I'm trying to connect tdbf component to the server but i can't.
The documentation does not tell anything about remote connections.
Can you recommend me some other options to do that?

A: Dbf1.filePath := '192.160.90.100:/F/shared-folder'; This looks like an NFS path which I don't believe TDBF supports. You will need to mount the relevant folder containing your DBF files on your local file system for TDBF to be able to access it properly.
However, I would strongly recommend you migrate your application away from DBF files and to a proper SQL-based client/server DBMS like Firebird, mySQL or PostgreSQL. There really is no valid reason for using 25+ year old desktop databases nowadays.


text:
Q: Why mysql is not storing data after "#" character? I have made one form in which there is rich text editor. and i m trying to store the data to database.
now i have mainly two problem..
1)  As soon as the string which contents "#"(basically when i try to change the color of the font)     character, then it does not store characters after "#". and it also not store "#" character also.
2)  although i had tried....in javascript
html.replace("\"","'");

but it does not replace the double quotes to single quotes.

A: We'll need to see some code. My feeling is you're missing some essential escaping step somewhere. In particular:

As soon as the string which contents "#"(basically when i try to change the color of the font) character

Implies to me that you might be sticking strings together into a URL like this:
var url= '/something.php?content='+html;

Naturally if the html contains a # symbol, you've got problems, because in:
http://www.example.com/something.php?content=

the # begins a fragment identifier called #123456">, like when you put #section on the end of a URL to go to the anchor called section in the HTML file. Fragment identifiers are purely client-side and are not sent to the server, which would see:
http://www.example.com/something.php?content=<div style="color:

However this is far from the only problem with the above. Space, < and = are simly invalid in URLs, and other characters like & will also mess up parameter parsing. To encode an arbitrary string into a query parameter you must use encodeURIComponent:
var url= '/something.php?content='+encodeURIComponent(html);

which will replace # with %35 and similarly for the other out-of-band characters.
However if this is indeed what you're doing, you should in any case you should not be storing anything to the database in response to a GET request, nor relying on a GET to pass potentially-large content. Use a POST request instead.

A: It seems that you are doing something very strange with your database code. Can you show the actual code you use for storing the string to database?
# - character is a common way to create a comment. That is everything starting from # to end of line is discarded. However if your code to store to database is correct, that should not matter.
Javascript is not the correct place to handle quote character conversions. The right place for that is on server side.

A: As you have requested....
I try to replay you... I try to mention exact what I had done...
1) on the client side on the html form page I had written like this..
html = html.trim();    // in html, the data of the rich text editor will come.
document.RTEDemo.action = "submit.php?method='"+ html.replace("\"","'") + "'";
\\ i had done replace bcz i think that was some problem with double quotes.

now on submit.php , my browser url is like this...
http://localhost/nc/submit.php?method='This is very simple recipe.
To make Bread Buttor you will need

bread

buttor

GOOD.

'

2) on submit.php   ........I just write simply this
echo "METHOD : ".$_GET['method'] . "

";
$method = $_GET['method'];

now my answer of upper part is like this...
METHOD : 'This is very simple recipe.

now i want to store the full detail of URL....but its only storing...
This is very simple recipe.


text:
Q: What is the use of testing_additional_tests.txt defined in testing.xml in Hybris? What is the use of file testing_additional_tests.txt defined in

hybris/bin/platform/resources/ant/testing.xml?

The code to access this file is pretty useless as well. First, it is deleted and then it is accessed!
<delete file="${HYBRIS_TEMP_DIR}/testing_additional_tests.txt"/>
            <trycatch property="foo" reference="bar">
                <try>
                    <echoxml file="${HYBRIS_TEMP_DIR}/testing_additional_tests.txt" append="true">
                        <additionalTests/>
                    </echoxml>
                </try>
                <catch/>
            </trycatch>

            <loadfile property="additional.tests" srcFile="${HYBRIS_TEMP_DIR}/testing_additional_tests.txt"/>


text:
Q: Understanding a simple circuit containing multiple op-amps I'm trying to learn electronics on my own. I got this circuit from an old audio amplifier device I had lying around. I'm trying to understand how it works. I have some questions about it. Could you help me?

*

*This point has a DC Voltage of +6V, and it oscillates in the range of a few mV in response to Audio In. Then the DC offset gets removed by the directly next capacitor. Is all of this correct? What's the point of all of it?

*If I short this capacitor, the amplifier stops working. Why? Current through Audio In is still flowing, right? Is the capacitor there to remove some DC offset?

*I don't think I understand what exactly the op-amps are doing and how they do it. I assume the transistors simply take the heavy work of providing the current needed to drive the Speaker once the input signal is completely amplified.

Edit:
I have redrawn the schematic. Also, I think I found the explanations by experimenting in Falstad Simulator:

*

*The DC Offset at the output of OA1 is slightly above +6V because of R2; C3 removes that offset. The output of OA1 oscillates by more than a few mV. The job of OA1 is to increase back the voltage of the input, since the input got lowered its voltage by the load it is put through.

*Through AudioIn is the path of least resistance to ground for the output of OA1 to go through, so C1 is there to remove that DC offset.

*Explained in the comments: "OA2 and OA3 are driving the two outputs to be opposite from each other, plus they reduce the effect of the class B outputs."

simulate this circuit – Schematic created using CircuitLab

A: A more conventional/understandable way of drawing the circuit diagram.


text:
Q: Loop in VBA to add extension .jpg I am really new to VBA and I would like to add a .jpg extension to values contained in a column.
Header Col G
11125;111545
154645
154511;145521;165421
1156556;13165
567418

I would like to loop into this column and add a .jpg to every value (multiple images per cell tho')
EDIT: 2n Try and working one
Sub image()
Dim c As Range

    For Each c In Selection.Cells
        Dim Words() As String
        Words() = Split(c.Value, ";")
        Dim x As Integer

        For x = 0 To UBound(Words)
        Words(x) = Words(x) & ".jpg"
        Next x
        c.Value = Join(Words, ";")
    Next
End Sub

Probably not the shortest way..but it works
Thank you

A: Here's a non-standard way to do it...
Select your cells
dim c as range
for each c in Selection.cells
    c.value = Join(Split(c.value,";"),".jpg;") & ".jpg"
    'This is what I'd actually use:
    'c.value = Replace(c.value, ";", ".jpg;") & ".jpg"
next

To answer your edited question, what you are doing wrong is:
c.Value = Words(x) & ".jpg"

Here you are overwriting the value of c.Value through each iteration and adding ".jpg", so it will only have the last value in the end.
If you want to keep using your method I'd suggest something like:
dim temp
temp = ""
for x = Lbound(Words) to Ubound(Words)
   temp = temp & Words(x) & ".jpg"
next x
c.value = temp

A: Sub image()
Dim c As Range

    For Each c In Selection.Cells
        Dim Words() As String
        Words() = Split(c.Value, ";")
        Dim x As Integer

        For x = 0 To UBound(Words)
        Words(x) = Words(x) & ".jpg"
        Next x
        c.Value = Join(Words, ";")
    Next
End Sub


text:
Q: C makefile to compile OpenGL project directly on iphone Please direct me if this question has already been asked; I did a search on the topic unable to find yet.
I am having trouble putting together a makefile that will take one or more .c OpenGL project files, uses apple-arm-darwin9 and OpenGL framework to compile into object directly on the iphone (using bash). For some reason whatever combination of framework or LIBPATH I use I am constantly seeing exceptions thrown - if anyone can point me to the right direction I'd be well on my way. Thanks

A: Too generic, and two different issues.
One, the problem of finding a command (or series of commands) that does correctly compile your code.
Two, writing a Makefile to do the job.
I'd help you with the latter, but you have to figure out the former first (which has nothing to do with Makefiles at all)...


text:
Q: hybridModel of Auto.arima and ANN produce point forecast outside of 95% CI I have been working on time series forecasting and recently read about how the hybrid model of auto.arima and ann provide better/more accurate forecasting results.
I have six time series data sets, the hybrid model work wonders for five of them but it gives weird results for the other.
I ran the model using the following to packages:
library(forecast)
library(forecastHybrid)
Here is the data:

ts.data

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
2012           1  16  41  65  87 104 152 203 213 263
2013 299 325 388 412 409 442 447 421 435 448 447 443
2014 454 446 467 492 525

Model:

fit <- hybridModel(ts.data, model="an")

Forecast results for the next 5 periods:

forecast(fit, 5)

   Point       Forecast    Lo 80    Hi 80    Lo 95    Hi 95
Jun 2014       594.6594 519.2914 571.0163 505.6007 584.7070
Jul 2014       702.1626 528.7327 601.8827 509.3710 621.2444
Aug 2014       738.5732 540.6665 630.2566 516.9534 653.9697
Sep 2014       752.1329 553.8905 657.3403 526.5090 684.7218
Oct 2014       762.7481 567.9391 683.5994 537.3256 714.2129

You see how the point forecasts are outside of the 95% confidence interval.
Does anybody know what this is happening and how I could fix it?
Any thoughts and insights are appreciated!
Thanks in advance.

A: See the description of this issue here
tl;dr nnetar models do not create prediction intervals, so these are not included in the ensemble prediction intervals. When the "forecast" package adds this behavior (on the road map for 2016), the prediction intervals and point forecasts will be consistent


text:
Q: tkinter - make a frame hide to the right with smooth "fading" animation I made a simple program where the main window has a frame hideout which will slowly move out of the screen
But it doesn't work
import tkinter as tk
from tkinter import ttk
import time

root = tk.Tk()
root.geometry('360x640')

hideout = tk.Frame(root, background= '#fff', width = 360, height= 640)
def initial(*args):
    for i in range(361):
        time.sleep(0.01)
        about.place(x=i,y=0)

root.after(0,initial)
root.mainloop()

What is wrong here?

A: You are using undefined variables: when calling place() on about, you probably mean hideout.
The "fading" can be controlled directly with root.after callbacks; use of time.sleep will block your GUI during an animation; this is undesirable.
Here is a working example:
import tkinter as tk

def initial(t=0):
    hideout.place(x=t, y=0)
    if t > 360:
        return
    root.after(10, initial, t+1)

if __name__ == '__main__':

    root = tk.Tk()
    root.geometry('360x640')
    hideout = tk.Frame(root, background='#fff', width=360, height=640)

    initial()
    root.mainloop()


text:
Q: mySQL php update How can I update a row in my mySql database from a HTML form. I have tried every technique and nothing seems to work. I would like that users could update their own profile page information.
I have a form on my page but the data doesn't get sent through.
What am i missing?
Here is my code:
------------INDEX.php
<?php
            require_once("inc/database.php");
            require_once("inc/query.php");
        ?>

User Profiles

                <?php
                while ($row = $results->fetch()) {

                    $id = ($row["id"]);
                    $name = ($row["name"]);
                    $age = ($row["age"]);
                    $password = ($row["password"]);

                    print '
';
                    print "
" . ($name) . "
";
                    print "
" . ($password) . "
";
                    print "
" . ($age) . "
";
                    print "
";

                }
                ?>

            <form action="inc/addnew.php" method="post">

Name: <input type="text" name="name" required>

ID: <input type="text" name="id" value="<?php echo $id; ?>">

<input type="submit" value="Lisää">

            </form>

------------QUERY.php
<?php

try{
    $results = $db->query("SELECT name, password, age, id FROM users");
    $results->execute();
    // echo "Our query ran successfully.";
} catch (Exception $e){
    echo "Data could not be retrived from the database.";
    exit;
}

------------DATABASE.php
<?php

try{
    $db = new PDO('mysql:host=localhost;dbname=user_profile;port=8889', 'User_profile','bFeLcZjMmVw4PBaF');
    $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    $db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
    echo "Could not connect to the database.";
    exit;
}

------------UPDATE.php
<?php
require_once("database.php");

if( isset( $_POST['name'] ) &&  strlen( $_POST['id'] )){

    $id = $_POST['id'];
    $name = $_POST['name'];

    $results=("UPDATE users SET name='$name' WHERE id=$id");
    }

        header("Location: ../index.php");
    }
else
    {
        //error either $_POST['login'] is not set or $_POST['login'] is empty form field
        echo 'Name or ID field was empty. Please fill out those fields. Back to site
';
    }

A: How you expect this query to execute?
$results=("UPDATE users SET name='$name' WHERE id=$id");

you are just generating a query here on UPDATE.php without actually doing anything with it.
Replace this line with:
$results = $db->query("UPDATE users SET name='$name' WHERE id=$id");

A: You need to prepare and execute your query, not just define it as a string:
$sth = $db->prepare("UPDATE users SET name=:name WHERE id=:id")

$sth->execute(array("name" => $_POST["name"], "id" => $_POST["id"]));

You should be using placeholders to insert your data. Your query uses string interpolation which is extremely dangerous due to SQL injection bugs. Do not put $_POST data directly into a query, it's never safe.


text:
Q: Newbie; Ember modal for create record I'm working on an app, and trying to figure out ember.
I have followed this: http://ember.guru/2014/master-your-modals-in-ember-js to getting my modals working, and I have no problem getting edit and delete to work, but I can't figure out how to get create working.
here is my link for edit:

and for create:

 New Address

my router for the section
this.resource('contact', {path: '/contact/:contact_id'}, function(){
    this.route('personage', {path: '/'});
    this.route('addresses');
    ...

the addresses is a belongs_to to contacts
Can someone please point me in the right direction, I have worked on this for days now!
UPDATE
route: contact.addresses.new
export default Ember.Route.extend({
    setupController: function(controller) {
        controller.set('fields', {})
    }
});

A: For the nested resources, you can use the route with last parts.
see more : http://emberjs.com/guides/routing/defining-your-routes/#toc_nested-resources


text:
Q: Enable mod_rewrite in Windows for .htaccess to work I want to run my Angular 6 app over Apache Tomcat server. But every time I reload when in deep link URL then it shows status 404 page not found.
So, for that, I included the .htaccess file in the root folder where my index.html is.
But still, it doesn't work because maybe the mod_rewrite is not enabled.
To enable mod_rewrite I was searching for httpd.conf file where I have to make the changes. But in my 'C:\Program Files\Apache Software Foundation\Tomcat 9.0' directory there is NO such file.
So how do i enable the mod_rewrite to make .htaccess work and reload my Angular app without an error?

A: Tomcat doesn't use httpd.conf, that is an apache file. The location of the individual webapps are kept in their individual web.xml files, but the location of all the configs are in ../tomcat8/conf/server.xml and web.xml
Try WAMP or Apache2 instead of Tomcat
You need to direct the .htaccess file to load the index.html on each hit.
like
DirectoryIndex index.html
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-s
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !\.(jpg|jpeg|png|gif|flv|mpeg|mpg|mp4)$
RewriteRule ^.*$ bootstrap.html [NC,L]

You will found this line in LoadModule rewrite_module modules/mod_rewrite.so in httpd.conf file, the file will be under the conf folder. you need to remove the hash(#) from it and then restart the apache services.
If you want that setup in Tomcat, then what I did in sample project is added the below code in webapps\ROOT\WEB-INF\web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">

  <display-name>Welcome to Tomcat</display-name>
  <description>
     Welcome to Tomcat
  </description>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

   <error-page>
    <error-code>404</error-code>
    <location>/test/index.html</location>
  </error-page>
</web-app>

Here /test/index.html test is my project name, you can change it to yours but try to use the project web.xml to avoid other project redirection. and in that case you can directly add the /index.html in path


text:
Q: How can I predict the asymptotic behavior of a function (not its numerical limit) by simplifying it? I have a complicated function which I intend to predict its asymptotic behavior (specially I have a $f(r)$ which I want to know its asymptotic behavior in $r\rightarrow \infty$). I know that the command Limit gives me the numerical limit of the function in the special limits instead, I need a function which simulate the behavior of the original function in the limits in the best possible way. Let me get help from a toy example:
We know the limit of Sin[x] for x->0 is 0 namely
Limit[Sin[x], x -> 0]
 (*0*)

but we know it behaves just as x function in small xs. The following plot shows this fact:
Plot[{Sin[x], x}, {x, 0, 4}, PlotLegends -> "Expressions"]

So we say x function simulates the asymptotic behavior of Sin[x]. I need to find such a thing for my complicated function. Note that I don't want use fitting or something else, I just want to reach such a function by manipulating (for example choosing terms whit high growth rate and removing other terms) my original function (what was not possible for simple Sin[x] function). Is there any command in Mathematica to do this?
Addendum
This is the closed form of my function:
f[re_] :=
  1/(8 Sqrt[2]
     mp re \[Gamma] (M^2 \[Beta] + mp^2 \[Gamma]) Sqrt[\[Beta] + (
     mp^2 \[Gamma])/M^2]) E^(-2 re^2 \[Gamma]) M^2 norm^2 \[Pi]^(
   3/2) (E^((M \[Alpha] - 2 mp re \[Gamma])^2/(
      2 (M^2 \[Beta] +
         mp^2 \[Gamma]))) ((-1 + E^((4 M mp re \[Alpha] \[Gamma])/(
           M^2 \[Beta] + mp^2 \[Gamma]))) M \[Alpha] +
        2 (1 + E^((4 M mp re \[Alpha] \[Gamma])/(
           M^2 \[Beta] + mp^2 \[Gamma]))) mp re \[Gamma]) +
     E^((M \[Alpha] - 2 mp re \[Gamma])^2/(
      2 (M^2 \[Beta] + mp^2 \[Gamma]))) (M \[Alpha] -
        2 mp re \[Gamma]) Erf[(M \[Alpha] - 2 mp re \[Gamma])/(
       Sqrt[2] M Sqrt[\[Beta] + (mp^2 \[Gamma])/M^2])] -
     E^((M \[Alpha] + 2 mp re \[Gamma])^2/(
      2 (M^2 \[Beta] + mp^2 \[Gamma]))) (M \[Alpha] +
        2 mp re \[Gamma]) Erf[(M \[Alpha] + 2 mp re \[Gamma])/(
       Sqrt[2] M Sqrt[\[Beta] + (mp^2 \[Gamma])/M^2])]);

where all parameters are real and positive. I want to find asymptotic behavior of f[re] when re goes to infinity.

A: Maybe this:
FullSimplify[
 Series[f[re], {re, Infinity, 1},
  Assumptions ->
   Thread[{γ, M, mp, norm, β, α} > 0]],
 Thread[{γ, M, mp, norm, β, α} > 0]]

FullSimplify[Normal[%],
 Thread[{γ, M, mp, norm, β, α} > 0]]
(*
-((E^((M (M α^2 -
     4 re (mp α + M re β) γ))/(
  2 (M^2 β + mp^2 γ))) M^3 norm^2 π^(
  3/2) (M α - 2 mp re γ))/(
 4 Sqrt[2] mp re γ (M^2 β + mp^2 γ)^(3/2)))
*)

Or, to remove an extra term:
FullSimplify[Normal@Series[%, {re, Infinity, 0}],
 Thread[{γ, M, mp, norm, β, α} > 0]]
(*
(E^((M (M α^2 - 4 re (mp α + M re β) γ))/(
 2 (M^2 β + mp^2 γ))) M^3 norm^2 π^(
 3/2))/(2 Sqrt[2] (M^2 β + mp^2 γ)^(3/2))
*)

Or to get the same thing:
FullSimplify[
 Asymptotic[f[re], re -> Infinity,
  Assumptions ->
   Thread[{γ, M, mp, norm, β, α} > 0],
  SeriesTermGoal -> 1],
 Thread[{γ, M, mp, norm, β, α} > 0]]


text:
Q: Creating indefinite matrix I need to create indefinite matrix for testing solver, which I am currently developing. What would be best way to proceed? Or what would be recommended topic to take a look at ?

A: A simple course of action is to pick any unital lower triangular matrix $L$ and a diagonal matrix $D$ with nonnegative diagonal entries and as many zeros on the diagonal as you like. The compute $A = LDL^T$ and feed it to your solver.

A: A $n\times n$ matrix is indefinite if there are both positive and negative eigenvalues.
The entries on the diagonal of a diagonal matrix are its eigenvalues.
So the simplest matrix is probably
$$
\left(
\begin{array}{rr}
-1 & 0 \\
 0 & 1
\end{array}
\right)
$$
For higher dimensions just fill up the diagonal, as you need.


text:
Q: How to update an existing cloudflare_record in terraform and github actions I creaed my project with code from Hashicorp tutorial "Host a static website with S3 and Cloudflare", but the tutorial didn't mention github actions. So, when I put my project in github actions, even though terraform plan and terraform apply output successfully locally, I get errors on terraform apply:
Error: expected DNS record to not already be present but already exists

 with cloudflare_record.site_cname ...
 with cloudflare_record.www

I have two resources in my main.tf, one for the site domain and one for www, like the following:
resource "cloudflare_record" "site_cname"  {
zone_id = data.cloudflare_zones.domain.zones[0].id
name    = var.site_domain
value   = aws_s3_bucket.site.website_endpoint
type    = "CNAME"
ttl     = 1
proxied = true
}

resource "cloudflare_record" "www" {
zone_id = data.cloudflare_zones.domain.zones[0].id
name    = "www"
value   = var.site_domain
type    = "CNAME"

ttl     = 1
proxied = true
}

If I remove these lines of code from my main.tf and then run terraform apply locally, I get the warning that this will destroy my resource.
Which should I do?

*

*add an allow_overwrite somewhere (don't see examples of how to use this in the docs) and the ways I've tried to add it generated errors.

*remove the lines of code from main.tf knowing the github actions run will destroy my cloudflare_record.www and cloudflare_record.site_cname knowing I can see my zone id and CNAME if I log into cloudflare so maybe this code isn't necessary after the initial set up

*run terrform import somewhere? If so, where do I find the zone ID and record ID

or something else?

A: Where is your terraform state? Did you store it locally or in a remote location?
Because it would explain why you don't have any problems locally and why it's trying to recreate the resources in Github actions.
More information about terraform backend (where the state is stored) -> https://www.terraform.io/docs/language/settings/backends/index.html
And how to create one with S3 for example ->
https://www.terraform.io/docs/language/settings/backends/s3.html

A: It shouldn't be a problem if Terraform would drop and re-create DNS records, but for better result, you need to ensure that GitHub Actions has access to the (current) workspace state.
Since Terraform Cloud provides a free plan, there is no reason not to take advantage of it. Just create a workspace through their dashboard, add "remote" backend configuration to your project and ensure that GitHub Actions uses Terraform API Token at runtime (you would set it via GitHub repository settings > Secrets).
You may want to check this example — Terraform Starter Kit

*

*infra/backend.tf

*infra/dns-records.tf

*scripts/tf.js
Here is how you can pass Terraform API Token from secrets.TERRAFORM_API_TOKEN GitHub secret to Terraform CLI:
- env: { TERRAFORM_API_TOKEN: "${{ secrets.TERRAFORM_API_TOKEN }}" }
  run: |
    echo "credentials \"app.terraform.io\" { token = \"$TERRAFORM_API_TOKEN\" }" > ./.terraformrc


text:
Q: How to minimize max value in Google OR-Tools? I am developing a model to solve a MILP problem using Google OR-Tools and Python. I have a problem with t tasks. Every task i needs w_i weeks to be completed and p_i_t workers on that specific week. There is a total time in weeks to complete all tasks. I need to optimize (min) the max value of workers needed in a particular week (variables to define: starting week for every particular task, or similar).
There is also a constraint: once a task starts, it should be finished. All tasks could run in parallel if needed.
Is it possible to model this problem using Google OR-Tools?. I have been trying to add a max Python function inside solver.Minimize but it is not working. How do I implement it correctly in Google OR tools?


text:
Q: LINQ query to include the parent name in the child item public class Order
{
    public int OrderId { get; set; }
    public DateTime OrderDate { get; set; }
    public bool MarkAsPresent { get; set; }

    public List<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int OrderItemId { get; set; }
    public int OrderId { get; set; }
    public int ProductId { get; set; }
    public int Quantity { get; set; }
    public decimal Price { get; set; }

    public Order Order { get; set; }
    public Product Product { get; set; }
}
public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
}

Please someone can help? From ASP.NET Core API controller, I need to return the following JSON. Please note that in the OrderItems, it includes the Product.ProductName. Also, if the Order.MarkAsPresent is true, then the productName should be replaced as 'Gift' in the JSON data.
{
    "order": {
        "orderId": "123",
        "orderDate": "01-May-2021",
        "orderItems": [
            { "productName": "Pen", "quantity": "25", "retailPrice": "3.50" },
            { "productName": "Paper", "quantity": "500", "retailPrice": "5.50" },
        ]
    }
}

A: The two answers given so far are far too cumbersome. There's a very common, standard way to do this:
var result = from o in context.Order
    select new
    {
        o.OrderId,
        o.OrderDate,
        OrderItems =
            from oi in o.OrderItems
            select new
            {
                ProductName = o.MarkAsPresent
                    ? "Gift"
                    : oi.Product.ProductName,
                oi.Quantity,
                RetailPrice = oi.Price
            }
    };

You didn't define RetailPrice, so I assume it's just OrderItem.Price. If you like, the two select new statement can be replaced by projections into named DTO classes like OrderDto and OrderItemDto, respectively.

A: You can do it  using an OrderDto.
        public class OrderDto
        {
           public int OrderId { get; set; }
           public DateTime OrderDate { get; set; }

           public object OrderItems { get; set; }

           public OrderDto(int orderId, DateTime orderDate)
           {
              OrderId = orderId;
              OrderDate = orderDate;
           }
        }//Cls

        //--------------------------------------------//

        public class OrderItemDto
        {
           public string ProductName { get; set; }
           public int Quantity { get; set; }
           public decimal RetailPrice { get; set; }
           public OrderItemDto(string giftName, int quantity, decimal retailPrice)
           {
              ProductName = giftName;
              Quantity = quantity;
              RetailPrice = retailPrice;
           }
        }//Cls

        //--------------------------------------------//

        public class GiftDto
        {
           public string GiftName { get; set; }
           public int Quantity { get; set; }
           public decimal RetailPrice { get; set; }

           public GiftDto(string giftName, int quantity, decimal retailPrice)
           {
              GiftName = giftName;
              Quantity = quantity;
              RetailPrice = retailPrice;
           }
        }//Cls

Add this method to your Order class
   public class Order
        {
           public int OrderId { get; set; }
           public DateTime OrderDate { get; set; }
           public bool MarkAsPresent { get; set; }

           public List<OrderItem> OrderItems { get; set; }

           public OrderDto ToDto()
           {
              var dto = new OrderDto(OrderId, OrderDate);
              if (MarkAsPresent)
                 dto.OrderItems = OrderItems.Select(oi => new GiftDto(oi.Product.ProductName, oi.Quantity, oi.Price));
              else
                 dto.OrderItems = OrderItems.Select(oi => new OrderItemDto(oi.Product.ProductName, oi.Quantity, oi.Price));

              return dto;
           }
        }//Cls

Then in your action return something like Ok(order.ToDto());
Examples:
       [HttpGet]
        [AllowAnonymous]
        public IActionResult OrderGift()
        {
           var order = new Order()
           {
              OrderId = 1,
              OrderDate = DateTime.Now,
              MarkAsPresent = true
           };
           order.OrderItems = new List<OrderItem>();

           for (int i = 0; i < 5; i++)
           {
              order.OrderItems.Add(
                 new OrderItem()
                 {
                    Order = order,
                    OrderId = order.OrderId,
                    OrderItemId = i + 10,
                    Price = (i + 1) * 10,
                    Product = new Product()
                    {
                       ProductId = i + 20,
                       ProductName = $"Name {i}"
                    },
                    ProductId = i + 20,
                    Quantity = i * 2 + 4

                 });
           }//for

           return Ok(order.ToDto());

        }///OrderGift

        [HttpGet]
        [AllowAnonymous]
        public IActionResult OrderRegular()
        {
           var order = new Order()
           {
              OrderId = 1,
              OrderDate = DateTime.Now,
              MarkAsPresent = false
           };
           order.OrderItems = new List<OrderItem>();

           for (int i = 0; i < 5; i++)
           {
              order.OrderItems.Add(
                 new OrderItem()
                 {
                    Order = order,
                    OrderId = order.OrderId,
                    OrderItemId = i + 10,
                    Price = (i + 1) * 10,
                    Product = new Product()
                    {
                       ProductId = i + 20,
                       ProductName = $"Name {i}"
                    },
                    ProductId = i + 20,
                    Quantity = i * 2 + 4

                 });
           }//for

           return Ok(order.ToDto());

        }//OrderRegular

A: You can also use the Linq's let clause:
var report =
    from o in orders
    let orderItems =
        from oi in o.OrderItems
        select new {
            productName = o.MarkAsPresent ? "Gift" : oi.Product.ProductName,
            quantity = oi.Quantity,
            retailPrice = oi.Price
        }
    select new {
        orderId = o.OrderId,
        orderDate = o.OrderDate,
        orderItems
    };

A: Use join to join the two models so we can connect every properties, and group all the
data by
OrderId and OrderDate, then just select the property you want to show.
About the gift,you can use if else in select.
Following is my demo:
[HttpGet]
    public JsonResult Get()
    {
        var model = (from e in _context.OrderItems.Include(x=>x.Order).ToList()
                     join y in _context.Products.ToList() on e.OrderItemId equals y.ProductId
                     group new { e, y } by new {  e.OrderId, e.Order.OrderDate } into g
                     select new
                     {
                         order = new
                         {
                             orderId = g.Key.OrderId,
                             orderDate = g.Key.OrderDate,
                             orderItems = (
                              from t in g.ToList()
                              select new
                              {
                                  productName = t.e.Order.MarkAsPresent == true ? "Gift" : t.y.ProductName,
                                  quantity = t.e.Quantity,
                                  retailPrice = t.e.Price
                              }
                             ).ToList()
                         }
                     }).ToList();

        return new JsonResult(model);
    }

Result:


text:
Q: cant install react-leaflet on my react project Running into an issue here where I cant install react-leaflet onto my project. I did
npm i react-leaflet

and it didn't work, and I even did
npm i leaflet.

What do I do here?

A: it might be for your node version (maybe you need to upgrade it)
you can try to delete your node_modules directory and also package.json the npm i again

*

*rm -R node_modules

*rm package-lock.json

*npm install
also adding --legacy-peer-deps at the end of installing your package might be helpful

*

*npm install react-leaflet --legacy-peer-deps


text:
Q: Trying to pull information from webpage I am trying to pull data from a website.  In my example case, I am running a search on Armorgames.com for the search term idle.  From there I would like to pull the name of each game and put it into a csv file for use later. My code:
$SearchResult = Invoke-WebRequest 'http://armorgames.com/search?type=games&q=idle'
($SearchResult.ParsedHtml.getElementsByTagName('H5') | Where { $_.pathname -like '/play*'})

Unfortunately, that won't output any results.  I can see the property names using:
$SearchResult.ParsedHtml.getElementsByTagName('H5')

Using the tag 'a' I can find games with a pathname containing 'play'.But I am having trouble filtering the results and then outputting the results to a file

A: $SearchResult.ParsedHtml.getElementsByTagName('a') | where-Object -Property pathname -Like 'play/*'

# select property pathname
$SearchResult.ParsedHtml.getElementsByTagName('a') |
    Where-Object -Property pathname -Like 'play/*' |
        Select-Object -Property pathname

# select property title
$SearchResult.ParsedHtml.getElementsByTagName('a') |
    Where-Object -Property pathname -Like 'play/*' |
        Select-Object -Property title -Unique

A: PowerShell Core (v6.0) compatible webscraping code, which should work with Windows PowerShell too, reliant on regex with the -match operator (as the ParsedHtml property isn't available on Core):
$SearchResult = Invoke-WebRequest 'http://armorgames.com/search?type=games&q=idle'
$GameNames = ($SearchResult.Content.split('<') |
    where {$_ -match '^a href.*play.*\ title=.*>[A-Z].*'}) -replace '.*>'
$GameNames

The output looks like this:
Artist Idle
Hero Simulator: Idle Adventures
Idle Farmer
Idle Online Universe
Idle Sword
Idle Web Tycoon
Legendary Journey Idle
NGU IDLE
Religious Idle
Zombidle

Now that you have an array of the names you wanted, you should be able to create a CSV with whatever additional information you need.


text:
Q: The value of a range that is variable I have a code which loops to the Sheet("Overview") if the value of Cells(Y,X) is equal to  " " then Y = Y + 1 otherwise the rest. The code runs fault on the part
If Range(Cells(Y,X).Address).Value = "" Then

If I put for instance "H4" in it works but not like this. What am I doing wrong with the Cells refence?
The whole code for the loop is:
Sub Maandag1()

Dim X As String
Dim Y As String
    X = 8
    Y = 4

    Do While Y <= 4

        If Sheets("Overview").Range(Cells(Y, X).Address).Value = " " Then
            Y = Y + 1
        Else
            With Sheets("Controle")
                .Range("B7").Value = Sheets("Overview").Range(Cells(Y, X).Address).Value
                .Range("B8").Value = Sheets("Overview").Range(Cells(Y, X + 1).Address).Value
                .Range("B13").Value = Sheets("Overview").Range(Cells(Y, X + 2).Address).Value
                .Range("B18").Value = Sheets("Overview").Range(Cells(Y, X + 3).Address).Value
                .Range("B23").Value = Sheets("Overview").Range(Cells(Y, X + 4).Address).Value
                .Range("B28").Value = Sheets("Overview").Range(Cells(Y, X + 5).Address).Value
            End With

            Y = Y + 1
        End If
    Loop

End Sub

A: Change that line of code to:
If Sheets("Overview").Cells(Y, X).Value = " " Then
No need to create the Range object with the .Cells method only to use that range to get the string address to use as a way to again build the range.
But the real problem here is that you've declared X and Y as strings. The .Cells operation wants to take long params
Dim X as Long
Dim Y as Long


text:
Q: Jasper Report Bands When No Data Source My understanding is that if you don't supply a JRDataSource to the JasperFillManager, then the resultant JasperReport will not contain any detail bands.
For reasons outside the context of this question, I want to place a few components (bar chart, and a table) on a small/simple JasperReport, and I want the data to come from a HashMap that I'll pass in. Thus, I don't need a JRDataSource implementation, which also means I won't get any detail bands.
So my question is: then what band(s) should I be adding my components to? The detail band is where I would normally add components to, but if I don't get a detail band, where does these orphaned components go?
Edit: Tangential to this question would be the obvious: how would I then calculate the size (height) that this band would need to be?

A: You can pass a JREmptyDatasource to the JasperFillManager. You can even specify how many virtual records you want, i.e. how many detail bands will be displayed, using the JREmptyDataSource#JREmptyDataSource(int count) constructor.

A: Put them in the Title or Summary band.
In effect your report will have no data. But since you're passing in a Map as a parameter with "data", then you are happy with this data-less report. Be sure the report is set to show "All Sections, No Detail" when there is no data.
With a chart you just set the chart height and band height however you want. A table component will expand... but that's not a problem. It can expand the Title or Summary band as needed.


text:
Q: How to get URL from WP database and open it? I have WordPress site and custom table in DB.
I need an user can enter promocode in the form, submit it, script find URL in the table by this promocode and open this URL in new window.
I insert this HTML in widjet
<form method="get" id="searchform" action="">
<input type="text" name="destination" id="destination" value="" />
<input type="submit" id="searchsubmit" value="GO" />
</form>

And insert this code in function.php
$q = $_GET["destination"];
$result = $wpdb->get_results( "SELECT url FROM mytable WHERE target = ".$q);
var_dump($result);

But how to open window?

A: You can do this task by doing ajax once you get success in that you can write the code for opening the website in new tab
Here is another option but i am not preferring this.
echo "<script> window.open(".$external_link.", '_blank') </script>";
     exit;


text:
Q: Конвертировать черно-белое изображение малого размера в матрицу того же размера на C++ Допустим есть черно-белое изображение размера 10x10 пикселей, то его нужно перевести в матрицу 10x10 в которой черному цвету будет соответствовать 1, а белому 0 или можно использовать 1 и -1 не важно собственно (что-то из этого). Желательно на языке C++.
unsigned char* readBMP(const char* filename)
{
int i;
FILE* f = fopen(filename, "rb");
unsigned char info[54];
fread(info, sizeof(unsigned char), 54, f); // read the 54-byte header

// extract image height and width from header
int width = *(int*)&info[18];
int height = *(int*)&info[22];

int size = 3 * width * height;
unsigned char* data = new unsigned char[size]; // allocate 3 bytes per pixel
fread(data, sizeof(unsigned char), size, f); // read the rest of the data at once
fclose(f);

for (i = 0; i < size; i += 3)
{
    unsigned char tmp = data[i];
    data[i] = data[i + 2];
    data[i + 2] = tmp;
}

for (int i = 0; i < width; i++) {
    for (int j = 0; j < height; j++) {
        cout << "R: " << (int)data[3 * (i * width + j)] << "; G: " << (int)data[3 * (i * width + j) + 1] << "; B: " << (int)data[3 * (i * width + j) + 2] << endl;
    }
}

return data;
}


text:
Q: Get key names in json file in delphi I have a json string format like this:
{
  "LIST":{
    "Joseph":{
      "item1":0,
      "item2":0
    },
    "John":{
      "item1":0,
      "item2":0
    },
    "Fred":{
      "item1":0,
      "item2":0
    }
  }
}

I need to get the names, "Joseph", "John", "Fred" and so on... I have a function that will add names to the list, I have no idea what names will be added so I need to get those names.
I can only get the name "LIST" with this code:
js := TlkJSONstreamed.loadfromfile(jsonFile) as TlkJsonObject;
try
 ShowMessage( vartostr(js.NameOf[0]) );
finally
 s.free;
end;

I'm using lkJSON-1.07 in delphi 7

A: You can get the names in turn and obtain the next object for each name.

*

*Get the name: js.NameOf[0]

*Obtain the object from the name: js[js.NameOf[0]]

The getJSONNames procedure prints all the names contained in a TlkJSONobject object recursively.
procedure getJSONNames(const Ajs: TlkJSONobject);
var
  i: Integer;
begin
  if Ajs = nil then
    Exit
  else
    for i := 0 to Ajs.Count-1 do begin
      WriteLn(Ajs.NameOf[i]);
      getJSONNames(TlkJSONobject(Ajs[Ajs.NameOf[i]]));
    end;
end;

var
  js: TlkJsonObject;
begin
  js := TlkJSONstreamed.loadfromfile(jsonFile) as TlkJsonObject;
  try
    getJSONNames(js);
  finally
    js.free;
  end;
end.


text:
Q: SAPI speech recognition training I want to make application which can recognize non-English words and I understand I have train SAPI in order to do that.
But how to do that ? I want to train my program to recognize non-English words and when I transfer it to another computer that it still recognizes these words and user on another computer can add other words.

A: Take a look at this article, it discusses Speach Recongition and the SRGS specification for saving Grammers. This MSDN Page discusses grammer format tags which include a LANGID tag


text:
Q: How do I use grunt-run to run a npm script? How do I run my 'test' npm script using Grunt? It says here that I can do it using grunt-run.
package.json
 .
 .
 "scripts": {
   "test": "jest"
   },
"jest": {
  "preset": "jest-exponent"
 }

.
.
.

"devDependencies": {
  "babel-jest": "^17.0.0",
  "babel-preset-react-native": "^1.9.0",
  "grunt": "^1.0.1",
  "grunt-run": "^0.6.0",
  "jest-exponent": "^0.1.3",
  "jest-react-native": "^17.0.0",
  "react-test-renderer": "^15.3.2"
}

Gulpfile.js - boilerplate code
module.exports = function(grunt) {
  grunt.initConfig({
   run: {
     options: {
       // Task-specific options go here.
     },
     your_target: {
       cmd: 'executable',
        args: [
               'arg1',
               'arg2'
        ]
     }
  }
})

}
What is the point of Grunt/Gulp if you can just use npm scripts? They require a lot less set up and do the same thing.

A: not sure if that will helps you, you need install first the task grunt-exec, in my sample i am runing a node server.js
this in my config.
Gruntfile.js
config.exec = {
         run_server: 'node server.js'
}
grunt.registerTask('serve', ['exec:run_server']);

package.json
 "grunt-exec": "^1.0.1",


text:
Q: Different DI scope for controller and queries in graphql-dotnet? I'm trying to implement a grahql-dotnet API.  I'm running into some weird behavior when I try to pass a scoped object into my controller and the same object into some of my services used by the queries using dotnet core dependency injection.
It seems that there is a different DI scope being used when the DI instantiates the controller and when it's instantiating objects used by the queries, because two separate objects are being passed in this instance.
Is this expected behavior or is this something that can be avoided?  I'm doing all of the same basic wiring for the controller and query as the star wars project.
Thanks in advance

A: GraphTypes are created only once per schema, when the Schema is initialized. So any dependencies of your GraphTypes are also created only once per schema. Schema is best left as a singleton for now due to the cost of initialization, so all your GraphTypes and their dependencies are also effectively singletons where query execution is concerned.
At the time of writing there is an open issue to investigate resolving dependencies on a per-execution basis.


text:
Q: How can I push an new item to an array which is the result of a method? Here is my code:
$this->results['twitter'] = array_push($this->twitter($request),"active");

It throws:

Only variables should be passed by reference

What's wrong and how can I fix it?

A: 1st : store the result in variable then push
$new_array = $this->twitter($request);
$this->results['twitter'] = array_push($new_array,"active");

Note : yes you can't pass the return result as a parameter . so you need to store it in variable and pass as a parameter . You can pass a variable by reference to a function so the function can modify the variable

A: Maybe you want something like this:
array_push($this->results['twitter'], $this->twitter());
This will push the return of the twitter() function into your array.
Beware that array_push only returns the number of the containing items.

A: Please note that array_push returns an integer representing the count of the array elements after addition. You can use array_merge instead:
$this->results['twitter'] = array_merge($this->twitter($request), ['active']);


text:
Q: Database Search with key words using jpa I'm doing college work where I have to search by keywords. My entity is called Position and I'm using MySQL. The fields that I need to search are:
    - date
    - positionCode
    - title
    - location
    - status
    - company
    - tecnoArea
I need to search the same word in all of these fields. To this end, I used criteria API to create a dynamic query. It is the same word for several fields and it should get the maximum possible results. Do you have any advice about how to optimize the search on the database. Should I do several queries?
EDIT
I will use an OR constraint.

A: Not sure what your database is.
If it is Oracle, you can use Oracle text.
The below link might be useful :
http://swiss-army-development.blogspot.com/2012/02/keyword-search-via-oracle-text.html

A: If you will need to find the key word at any position within the data you will need to use LIKE with wildcards, eg. title LIKE '%manager%'. Since date and positionCode (presumably a numeric type) are not likely to contain the key word, to achieve a very small performance gain, I would omit searching these columns for the key word. Your query is going to need to do a serial read, which means that all rows in the table will need to be brought into main memory to evaluate and retrieve the result set of your query. Given a serial read is going to happen anyway, I do  not think there is too much you can do to optimize the query when searching multiple columns. I am not familiar with the "criteria api to create dynamic queries", but using dynamic queries in other systems is non-optimal - they must be parsed and evaluated every time the are run and most query optimize-rs cannot make use of the statistics for cost-based optimization to improve performance like they can with explicitly defined SQL.


text:
Q: How to pass SqlDbType.udt to stored procedure? I'm trying to execute a stored procedure using ADO.NET. The stored procedure has  few parameters of UDT type. I'm using below code to call the stored proc and passing parameter but it looks like the value being passed to proc is not the one that I'm passing but default value of that type.
  using (SqlCommand cmd = new SqlCommand(procName, _conn))
        {
            if (input != null)
            {
                foreach (Parameter inputPair in input)
                {
                    SqlParameter sp = new SqlParameter("@" + inputPair.Name, inputPair.Type);
                    sp.Value = inputPair.Value;
                    sp.Direction = System.Data.ParameterDirection.Input;

                    if (!string.IsNullOrEmpty(inputPair.UdtTypeName))
                    {
                        sp.SqlDbType = SqlDbType.Udt;
                        sp.UdtTypeName = inputPair.UdtTypeName;
                    }

                    if (0 != inputPair.Size)
                    {
                        sp.Size = inputPair.Size;
                    }
                    cmd.Parameters.Add(sp);
                }
            }

Any pointer is much appreciated .


text:
Q: Using jna lib to write to registry throws either access is denied or System cannot find the file specified(lib not loaded) So i have application that needs to use JNA lib to write to registry, when i want to run it from netbeans i get Access is denied i guess i dont have permissions to write with Advapi32Util.registrySetIntValue
So i created batch file that run my application with administrator privileges and did same thing now i got The system cannot find the file specified when i get to Advapi32Util.registrySetIntValue
To see better here is a screen:
On the left you see my netbeans execution and on the right batc hfile execution with admin privileges.I do have lib folder filled with same libraries , When you look at console of command promt you see VALUE READ:-1 , that means i cant even read with the library jna.platform.win32 Why is my library not loaded?

I use jnativehook that is in the folder lib and that one is loaded no problem , netbeans execution also loaded jna.platform.win32 as you can see i coud read value 1 instead of no value has been read -1
I have no idea what is happening there must be something wrong, both libraries are in the same folder, same imports its exactly the same .jar file beign coppied to test folder for jars
So question , why i get this result? Why is my lib not loaded when i can load library jnativehook that is in the same folder and use it normally bud jna throws error?Dont forget that everything loads well in netbeans , i just lack necessery privileges to run writing to registry(i can read from registry with no problem).
Additional not so important code information:
Imports:
import com.sun.jna.platform.win32.Advapi32Util;
import com.sun.jna.platform.win32.WinReg;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;

Reading method:
  public static final int readFromLEProperties(String guid) {

        System.out.println("GUID IS:" + guid);

        try {
            int valueInReg = Advapi32Util.registryGetIntValue(

                    WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\"
                    + "Audio\\Render\\" + guid + "\\FxProperties", "{E0A941A0-88A2-4df5-8D6B-DD20BB06E8FB},4");
            System.out.printf("LE Value: %s\n", valueInReg);
            return valueInReg;
        } catch (Exception e) {
            System.out.println("Coudnt read value from properties path:" + "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\"
                    + "Audio\\Render\\" + guid + "\\FxProperties   NAME:" + "{E0A941A0-88A2-4df5-8D6B-DD20BB06E8FB},4");
        }

        return -1;
    }

And writing method:
 public static final void writeToLEProperties(String guid, boolean activateLE) {

        try{
              Advapi32Util.registrySetIntValue(WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\"
                + "Audio\\Render\\" + guid + "\\FxProperties", "{E0A941A0-88A2-4df5-8D6B-DD20BB06E8FB},4", (activateLE) ? 1 : 0);
        }catch(Exception e){
            System.out.println("Error: AD");
        }
}


text:
Q: Ruby Date Formats If a user enters a search value in this format MM/DD/YYYY the following works:
date = Date.strptime(search_value, "%m/%d/%Y")
How can I accommodate if the user enters it like these:
MM-DD-YYYY - notice the dash instead of the slash
M-D-YYYY
M/D/YYYY
Currently, I am getting an invalid date if one of those are entered. I am trying to cover all of the different formats.

A: date = Date.new(*search_value.scan(/\d+/).map(&:to_i).rotate(-1))

A: If you want to cover all your bases, and not reinvent the wheel, take a look at https://github.com/mojombo/chronic

A: You can use gsub or gsub! method to replace dash to slash:
for example:
"04-01-2014".gsub("-","/")
this gives you result as below:
04/01/2014
i don`t know rest of the format you encountered, if you want help please
show other formats also.


text:
Q: Using HTML in jQuery UI autocomplete Before jQuery UI 1.8.4 I could use HTML in the JSON array I built to work with an autocomplete.
I was able to do something like:
$row_array['label'] = 'User, Name';

That would show up as red text in the drop down.
As of 1.8.4 that does not work. I found http://dev.jqueryui.com/ticket/5275 which tells me to use the custom HTML example here which I have had no luck with.
How can I go about getting HTML to show up in the suggestion?
My jQuery is:

My JSON array includes HTML like the following:
[{"label":"User, Name","value":"User, Name","id":"10"}]

A: This solution is not recommended but you can just edit source file jquery.ui.autocomplete.js (v1.10.4)
Original:
_renderItem:function(t,i){return e("
").append(e("").text(i.label)).appendTo(t)},

Fixed:
_renderItem:function(t,i){return e("
").append(e("").html(i.label)).appendTo(t)},

A: Add this to your code:
).data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "

" )
                .data( "item.autocomplete", item )
                .append( ""+ item.label + "" )
                .appendTo( ul );
        };

So your code becomes:

Note: On old versions of jQueryUI use .data("autocomplete")" instead of .data("ui-autocomplete")

A: This is also documented in jquery-ui autocomplete documentation at:
http://api.jqueryui.com/autocomplete/#option-source
The trick is:

*

*Use this jQuery UI extension

*Then in autocomplete option pass autocomplete({ html:true});

*Now you can pass html <div>sample</div> in "label" field of JSON output for autocomplete.

If you don't know how to add the plugin to JQuery UI then:

*

*Save the plugin(Scott González' html extension) in a js file or download the js file.

*You have already added the jquery-ui autocomplete script in your html page(or the jquery-ui js file). Add this plugin script after that autocomplete javascript file.

A: I had the same issue, but I prefer to use a static array of options for my option('source') for performance. If you tried that with this solution, you'll find that jQuery searches on the entire label too.
EG if you supplied:
[{"label":"User, Name","value":"User, Name","id":"10"}]

Then typing "span" would match both results, to get it to search on the value only override the $.ui.autocomplete.filter function:
$.ui.autocomplete.filter = function(a,b){var g=new RegExp($.ui.autocomplete.escapeRegex(b),"i");return $.grep(a,function(c){return g.test(c.value||c)})}

You can edit the last parameter c.value to anything you want, e.g. c.id || c.label || c.value would allow you to search on label, value, or the id.
You can supply as many key/values to autocomplete's source parameter as you want.
PS: the original parameter is c.label||c.value||c.

A: I had the issue mentioned by Clarence. I needed to supply HTML to make a nice appearance with styles and images. This resulted in typing "div" matching all elements.
However, my value was only an ID number, so I couldn't allow the search to run off of just that. I needed the search to look for several values, not just the ID number.
My solution was to add a new field that held only the search values and check for that in the jQuery UI file. This is what I did:
(This is on jQuery UI 1.9.2; it may be the same on others.)
Edit filter function on line 6008:
filter: function (array, term) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
        return $.grep(array, function (value) {
            if (value.searchonly == null)
                return matcher.test(value.label || value.value || value);
            else
                return matcher.test(value.searchonly);
        });
    }

I added the check for the "value.searchonly" field. If it is there, it uses that field only. If it is not there, it works as normal.
Then you use the autocomplete exactly as before, except you can add the "searchonly" key to your JSON object.
I hope that helps someone!


text:
Q: Can we add a link to the chat "FAQ" page in the description of the privilege? A lot of new chat users (myself included) begin by asking someone in the room how to use the chat system. I think an easy-to-find link to the chat "Frequently Asked Questions" page would help people feel more comfortable. There is a link in the chat room itself, but it's in tiny blue lower-case letters at the bottom of the page.
I propose adding a link on the Help Center > Privileges page, in the description of the privilege. It would look something like this:
20 talk in chat Participate in this site's chat rooms.


text:
Q: JS unit test with Jasmine I am very new to Jasmine, infact I just started today and don't have prior knowledge writing JS unit test cases. I am trying to write a simple test case in Jasmine in order to test a very basic JS code. I have added all the necessary scripts and libraries in my project.
So here is the piece of JS code. I am fetching the local Australian date and time and arranging them in a particular format.
var date = {

    formatFullDate: function(date) {
        var localDate = this.getLocalTimeFromAustraliaTime(date),
            month = this.addZeroToFront(localDate.getMonth() + 1),
            hour = this.addZeroToFront(localDate.getHours()),
            minute = this.addZeroToFront(localDate.getMinutes());

        return localDate.getDate() + '/' + month + '/' + localDate.getFullYear() + ' ' + hour + ':' + minute;
    },

    formatTime: function(date) {
    var localDate = this.getLocalTimeFromAustraliaTime(date),
        hour = this.addZeroToFront(localDate.getHours()),
        minute = this.addZeroToFront(localDate.getMinutes());

    return hour + ':' + minute;
    },

    addZeroToFront: function(whatever) {
    if (whatever < 10) whatever = "0" + whatever;
    return whatever;
    },

    getUTCtimeOffset: function() {
    var date = new Date();
    return date.getTimezoneOffset();
    },

    getLocalTimeFromAustraliaTime: function (date) {
    var utcTime = new Date(date.getTime() - 11*60*60*1000),
        localDate = new Date(utcTime - this.getUTCtimeOffset()*60*1000);
    return localDate;
    }
}

In the above mentioned code I can test various things for example the function is fetching the correct timezone, adding 0 prior to the time, formatting the date, etc.
I would like to know how do I structure my test case. I could think of the possible structure
describe( "Australian full date format", function () {

    describe( "Time format", function () {
        it("Check if time format is fetched correctly", function () {
            expect(something).toEqual(something);
        });
    });

    describe( "Adding 0 to the front", function () {
        it("Check if 0 is added prior to the time", function () {
            expect(something).toEqual(something);
        });
    });

    describe( "Get local Australian time", function () {
        it("Check if correct Australian time is fetched", function () {
            expect(something).toEqual(something);
        });
    });

    it("Check if the date is formatted correctly", function () {
        expect(something).toEqual(something);
    });
});

If I am in the right direction then how do I move forward from this point onward. I am quite confused how to write the equivalent test case for my JS code.

A: I would create tests something like this:
describe("Australian full date format", function() {
  describe("#formatFullDate", function() {
    it("should have format 'date/month/year hour:min'", function() {
      //...
    });
  });

  describe("#formatTime", function() {
    it("should have format 'hour:min'", function() {
      //...
    });
  });

  describe("#addZeroToFront", function() {
    describe("if whatever < 10", function() {
      it("should add 0 to front", function() {
        //...
      });
    });
    describe("if whatever >= 10", function() {
      it("should return original without any changes", function() {
        //...
      });
    });
  });

  //...
});

So I used describe to show what function is being tested. Then used describe for conditions. Used it to test only one feature of a function. All external objects (Date in this case) should be stubbed to test functions getUTCtimeOffset and getLocalTimeFromAustraliaTime.


text:
Q: OOP PHP - Returning $connection from functions (please see code) Procedural PHP works for me, but when I try to code like I do in objective C I cannot seem to get the functions to work. I think it has something to do with my variable scope and the functions not returning any values. Where am I going wrong with my code here?
      <?php

      require_once("constants.php");

      class Main {

public $menu;
public $connection;

function connectToDatabase() {
    //connect to database & check connection
    $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " .      mysqli_connect_error(); }
}

function queryDatabase($select, $from) {
    $result = mysqli_query($connection,"SELECT $select FROM $from");
}

function closeDatabaseConnection() {
    mysqli_close($connection);
}

function displayMenu() {

    //connect to database & check connection
    connectToDatabase();

    //get menu data
    queryDatabase(*, pages);

    //construct menu data
    echo '
';
    while($row = mysqli_fetch_array($result))
        {
            echo '
';
            echo $row['menu_name'];
            echo '
';
        }
    echo '
';

    //close connection
    closeDatabaseConnection();
}

function displayFooter() {

}

function getUser() {

}

function userLogIn() {

}

  }
?>

A: Instead of using $connection, you should use $this->connection, and run it like so:
$Db = new Main();

$Db->connectToDatabase();

If you want to access a property inside a method, make sure to reference it with $this->prop, rather than just $prop. If the method is static, use self::prop instead.
$this refers to the current instantiation of the class. You would use the scope resolution operator (::) if the method/property is static (DBConnection::connection DBConnection::connectToDatabase())/
Also, I'd rename class 'Main' to something else like DBConnection (PHP doesn't use main methods like C does), then:
$Db = new DBConnection();
$Db->connectToDatabase();

Because in PHP, although you can have one class in one PHP file named connection.php, with a class of Main, if you have another class following the same pattern, then you'll have two Main classes.

A: if you want to use a method or variable inside it's own class, you have to put $this-> in front of it. For exmaple this connectToDatabase(); would become this $this->connectToDatabase();

A: There are all kinds of things wrong with this class, so I will focus on a few key points and maybe you can fix it from there without us having a total rewrite
First, consider this:
public $connection;

function connectToDatabase() {
    //connect to database & check connection
    $connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " .      mysqli_connect_error(); }
}

You declare a class variable $connection, which is ok. But in your function you assign a local variable instead of accessing the class variable. From within a class, you would call all class members using $this. So the function should be:
function connectToDatabase() {
    //connect to database & check connection
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " .      mysqli_connect_error(); }
}

Now, other methods attempt to call functions but they need to do the same thing:
function displayMenu() {

    //connect to database & check connection
    // this should just check to see if $connection is populated. if not then call this method
    $this->connectToDatabase();

And this method is not accessing the class var for connection:
function queryDatabase($select, $from) {
    $result = mysqli_query($this->connection,"SELECT $select FROM $from");
}

those few examples should give you the basic idea of accessing class methods and variables. You can ask specific questions and we may update, but for now this should get you going.

A: Here is a mysqli connection class that I use regularly. It might not answer your question but you can study it and it should help you better understand the concept. It did for me anyway.
class DBConnection
{
    protected $mysqli;
    private  $db_host='localhost';
    private  $db_name='';
    private  $db_username='';
    private  $db_password='';

    public function __construct() {
        $this->mysqli = new mysqli($this->db_host,$this->db_username,
        $this->db_password, $this->db_name) or die($this->mysqli->error);

        return $this->mysqli;
    }

    public function getLink() {
        return $this->mysqli;
    }

    public function query($query) {
        return $this->mysqli->query($query);
     }

    public function real_escape_string($str) {
        return $this->mysqli->real_escape_string($str);
    }

    function __destruct(){
        $this->mysqli->close();
    }
}

And then when you need to connect to the database in another class call it in the construct function like so:
public function __construct(DBConnection $mysqli) {
    $this->mysqli = $mysqli->getLink();
}


text:
Q: Preserve damaged TrueCrypt partition before repairs I've got a TC partition damaged by Windows installation. In its inifinite wisdom Windows thinks it is okay to use random "unoccupied" HDD plugged in PC as it sees fit and puts a small boot partition here even when told to be installed elsewhere, thus overwriting TC header and most (or all) of encrypted volume metadata. I've managed to mount partition with TC by using spare footer, and will proceed to fiddle with different repair/data extractions tools to get several important files from there.
Before I start, I would like to preserve entire damaged partition in some way so if any of tools make things worse I could rollback to current state. If possible, I would also like to convert this partition to TC container file, so rolling back would be as simple as just copying it. How do I do that?

A: The best way to preserve a damaged volume is to use a sector-by-sector image-based using advanced backup software like Acronis Backup & Recovery.  It is file-agnostic and just cares about backing up every sector.  Bear in mind you must configure it to these settings.  Alternatively you could by a disk drive replicator and clone the drive using the replicator to another drive.
Once backed up, attempt decryption.
Hope this helps!


text:
Q: Advanced classical electrodynamics book As I have already studied Griffiths, I want something with modern and advanced approach both towards theory and problem solving.

A: The canonical advanced textbook for E&M is Jackson.  I don't know if it is really considered modern, but it is still taught in my graduate program at UC Berkeley.


text:
Q: Control which multi fields are queried by default I have a preexisting index that contains field mappings and is currently being queried by many applications. I would like to add additional ways for the data to be queried, specifically, support full text search via analysis. Multi-fields seemed like the obvious way to do this, but I found that adding new multi-fields actually changes the existing query behavior.
For example, I have an "id" field that is a keyword. Applications are already using this field to query on. After I add a new multi-field, like "txt" (using the standard analyzer), new documents can be found by querying with just a partial value match. Values for "id" look like this: "123-abc" so now a query with just "abc" will match when querying against the "id" field. This is not how it worked previously (the keyword only field would require the entire value "123-abc").
Ideally, the top-level "id" field would be keyword only, and if a "full text" search was required, the query would need to specify "id.txt". So my question is... is there a way to disable multi-fields and require that the query explicitly set a sub field when needed?
My only other thought on how to solve this, was to use copy_to so that these fields are completely distinct... but that is a bit more work and there are many many fields to deal with that would require this.


text:
Q: How to know when a user launch an activity in my app I have an app that shows a list of places to visit in my province. When users tap somewhere, the app launches a new activity that shows specific information about that place. How can I know that the user has launched the activity of specific information and which of the places was?
Thak you for your time,
flagg327

A: When you start your activity add extras to the intent.
    Intent newIntent = new Intent(this, YourActivity.class);
    newIntent.putExtra("KEY", "VALUE");
    startActivity(newIntent);

Then from your second activity retrieve the data bundled with that intent.
    String value = getIntent().getExtras().getString("KEY");

A: Can use the  package : android.app.usage
Has the following Classes :
ConfigurationStats ,NetworkStats, NetworkStats.Bucket, NetworkStatsManager , UsageEvents ,  UsageEvents.Event, UsageStatsManager
enter link description here

A: Use flurry. Create project on flurry.com and it will give you an app id.
download the .jar file and put it in apps "libs" folder.
And then in your activity:
in onCreate():
FlurryAgent.init(this, "YOUR_APP_ID");

and in onStart() and onStop():
@Override
public void onStart()
{
    super.onStart();
    FlurryAgent.onStartSession(this, "YOUR_APP_ID");
    FlurryAgent.logEvent("YOUR_ACTIVITY_NAME");

}
@Override
public void onStop()
{
    super.onStop();
    FlurryAgent.onEndSession(this);

}

and then when you login to flurry.com, in your project you can see the full log of that activity, even if the app crashed on that activity, you will get crash report.
You can use google analytics also.


text:
Q: Keyboard in not appearing correctly in web view - Landscape mode I'm presenting custom web view like this.
let vc = CustomWebViewVC.viewController()
    vc.delegate = self
    present(vc, animated: true, completion: nil)

I've implemented this to show custom web view in landscape mode.
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .landscapeRight
}

//----------------------------------------------------------

override var shouldAutorotate: Bool {
    return false
}

Issue
CustomWebViewVC is correctly opens in landscape mode but when I click on textfield inside of webivew this happens.

I don't know what is the issue is.
Any suggestions?

A: The missing method was this
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.landscapeRight
}

After adding this in view controller did the trick.
To open viewcontroller in landscape mode you need to implement all three method as I did.
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return .landscapeRight
}

//----------------------------------------------------------

override var shouldAutorotate: Bool {
  return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.landscapeRight
}

A: Add following code in viewDidLoad
Swift 4
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")


text:
Q: ViewModel assigned an object, how can I pass that back into the Post? So I have two methods:
    public ActionResult Create(Guid id)
    {
        Assignment viewModel = new Assignment();
        viewModel.Classroom = classroomRepository.GetByID(id);
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult Create(Assignment assignment)
    {
        if (ModelState.IsValid)
        {
            assignmentRepository.Insert(assignment);
            assignmentRepository.Save();
            return RedirectToAction("Index");
        }
        return View(assignment);
    }

As you can see, when I load up my Create page, I'm loading a Classroom into the viewModel. This works and displays the correct Classroom on the View.
My problem occurs when I POST to the Create method, my assignment object I pass in now doesn't include (it's NULL) Classroom that I passed in on GET.
EDIT ~ To Show View:
@model My_School_Book.Models.Assignment
@{
    ViewBag.Title = "Create";
}

Creating New Assignment:

        @using (Html.BeginForm("Create", "Assignment", FormMethod.Post, new { @class = "form-horizontal" }))
        {
            @Html.ValidationSummary(true)

                @Html.LabelFor(model => model.Classroom.Name, "Classroom", new { @class = "control-label" })

                    @Html.DisplayTextFor(model => model.Classroom.Name)

                @Html.LabelFor(model => model.Name, new { @class = "control-label" })

                    @Html.TextBoxFor(model => model.Name)
                    @Html.ValidationMessageFor(model => model.Name)

                @Html.LabelFor(model => model.Description, new { @class = "control-label" })

                    @Html.TextAreaFor(model => model.Description)
                    @Html.ValidationMessageFor(model => model.Description)

                @Html.LabelFor(model => model.AssignedDate, new { @class = "control-label" })

                        @Html.TextBoxFor(model => model.AssignedDate)

                    @Html.ValidationMessageFor(model => model.AssignedDate)

                @Html.LabelFor(model => model.DueDate, new { @class = "control-label" })

                        @Html.TextBoxFor(model => model.DueDate)

                    @Html.ValidationMessageFor(model => model.DueDate)

                @Html.LabelFor(model => model.Weight, new { @class = "control-label" })

                    @Html.TextBoxFor(model => model.Weight, new { @class = "span2" })
                    @Html.ValidationMessageFor(model => model.Weight)

                @Html.LabelFor(model => model.Total, new { @class = "control-label" })

                    @Html.TextBoxFor(model => model.Total, new { @class = "span2" })
                    @Html.ValidationMessageFor(model => model.Total)

                <button type="submit" class="btn btn-primary"> Create</button>
                 Cancel

        }

@section Scripts
{

}

A: You are only including Classroom.Name, thus on the form post nothing is there for the model binder to populate your model with.
Do you really need the classroom populated back though? What are you trying to accomplish?
If you need the ID simply write it out as:
@Html.HiddenFor(o=>o.Classroom.ClassroomId)
(or whatever the id is) and load it back up on the server side.
If you really need it there - you can write it out as inputs via
@Html.EditorFor(o=>o.Classroom)
That then allows the end user to modify it which I dont think you want, thus I'd use the ID (guid).

A: If you want that Classroom survive post then you need to add it to form in hiddenfield:
Just add this into form:
@Html.HiddenFor(m=m.Classroom.ClassroomId)
@Html.HiddenFor(m=m.Classroom.ClassroomName)

A: I ended up using a View Model:
public class AssignmentCreateData
{
    public Guid ClassroomID { get; set; }
    public String ClassroomName { get; set; }
    public Assignment Assignment { get; set; }
}

and my controller looked like this:
    public ActionResult Create(Guid id)
    {
        AssignmentCreateData viewModel = new AssignmentCreateData();
        Classroom classroom = classroomRepository.GetByID(id);
        viewModel.ClassroomID = classroom.ClassroomID;
        viewModel.ClassroomName = classroom.Name;
        viewModel.Assignment = null;
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult Create(AssignmentCreateData viewModel)
    {
        if (ModelState.IsValid)
        {
            viewModel.Assignment.ClassroomID = viewModel.ClassroomID;
            assignmentRepository.Insert(viewModel.Assignment);
            assignmentRepository.Save();
            return RedirectToAction("Index");
        }
        return View(viewModel);
    }

Then my View includes:
@Html.HiddenFor(model => model.ClassroomID)


text:
Q: pass list as parameter to udf pyspark My json schema looks like this
 {
  "uid": "a7f2e98835c1fb67e9aa9f1fbaae5e98",
  "gender": "F",
  "click": [
    {
      "url": "htp://abc.com/1.html?utm_campaign=397"
    },
    {
      "url": "htp://qaz.com/1.html?utm_campaign=397"
    }
  ]
}

i have udf that clean visits.url, for example my_udf("htp://abc.com/1.html?utm_campaign=397") i get abc.com
I want to get dataframe with cleansed url:
uid                              gender    urls
a7f2e98835c1fb67e9aa9f1fbaae5e98 F         [abc.com,qaz.com]

My code:
from pyspark.sql import functions as F
from pyspark.sql.types import *

import re
from urllib.parse import urlparse
from urllib.request import urlretrieve, unquote

clean = F.udf (lambda z:my_udf(z), ArrayType(StringType()))

def my_udf(url):
    url = re.sub('(http(s)*://)+', 'http://', url)
    parsed_url = urlparse(unquote(url.strip()))
    if parsed_url.scheme not in ['http','https']: return None
    netloc = re.search("(?:www\.)?(.*)", parsed_url.netloc).group(1)
    if netloc is not None: return str(netloc.encode('utf8')).strip()
    return None

dataFrame = spark.read.json('1.json') \
.withColumn("urls", clean(F.col("click.url"))) \
.select( F.col("uid"), F.col("gender"), F.col("urls") ) \
show(3)

But i get errors:
TypeError: expected string or bytes-like object

What am i doing wrong?

A: i did it:
dataFrame = spark.read.json('1.json') \
    .withColumn("urls_exploded",  F.explode(  F.col("click.url") )) \
    .withColumn("urls_cleaned", my_udf(F.col("urls_exploded"))) \
    .groupBy(F.col("uid"),F.col("gender") ) \
    .agg(F.collect_set(F.col("urls_cleaned")).alias("urls") ) \
    .select( F.col("uid"), F.col("gender_age"), F.col("urls") ) \
    .show(1,truncate=False)


text:
Q: Parsing XML childNodes of a given name tag? How do you parse the individual child nodes of a given tag name in the order they appear?  For instance, in the example below, i want to parse the each "rule" tag children in the order they appear:
<?xml version="1.0" encoding="UTF-8"?>
  <rules>
    <rule>
        <if name="Uniformity of Cell Size" operator="lessOrEqual" value="2.5"/>
        <if name="Bare Nuclei" operator="lessOrEqual" value="5.5"/>
        <then class="class" score="2" operator="equal"/>
    </rule>
    <rule>
        <if name="Uniformity of Cell Size" operator="lessOrEqual" value="2.5"/>
        <if name="Bare Nuclei" operator="greaterThan" value="5.5"/>
        <then class="class" score="4" operator="equal"/>
    </rule>
  </rules>

Expected output:
Uniformity of Cell Size  lessOrEqual 2.5
Bare Nuclei lessOrEqual 5.5
class  equal 2

Uniformity of Cell Size  lessOrEqual 2.5
Bare Nuclei greaterThan 5.5
class  equal 4

A: A - Demo Code : DOMParserExample.java
import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMParserExample {

    public static void main(String[] args) {

        try {
            File fXmlFile = new File("sample.xml");
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);

            doc.getDocumentElement().normalize();
            //System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

            NodeList nodeList = doc.getElementsByTagName("rule");
            //System.out.println("----------------------------");

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                NodeList children = node.getChildNodes();
                for(int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    switch(child.getNodeName()) {
                        case "if": {
                            printIfNode((Element) child);
                            break;
                        }
                        case "then": {
                            printThenNode((Element) child);
                            break;
                        }
                    }
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // specialized print method for 'if'
    private static void printIfNode(Element element) {
        String name     = element.getAttribute("name");
        String operator = element.getAttribute("operator");
        String value    = element.getAttribute("value");
        System.out.printf("%s %s %s\n", name, operator, value);
    }

    // specialized print method for 'then'
    private static void printThenNode(Element element) {
        String cLass    = element.getAttribute("class");
        String operator = element.getAttribute("operator");
        String score    = element.getAttribute("score");
        System.out.printf("%s %s %s\n", cLass, operator, score);
    }

}

B - Sample File: sample.xml
<?xml version="1.0" encoding="UTF-8"?>
<rules>
    <rule>
        <if name="Uniformity of Cell Size" operator="lessOrEqual" value="2.5"/>
        <if name="Bare Nuclei" operator="lessOrEqual" value="5.5"/>
        <then class="class" score="2" operator="equal"/>
    </rule>
    <rule>
        <if name="Uniformity of Cell Size" operator="lessOrEqual" value="2.5"/>
        <if name="Bare Nuclei" operator="greaterThan" value="5.5"/>
        <then class="class" score="4" operator="equal"/>
    </rule>
</rules>

C - Sample Output
Uniformity of Cell Size lessOrEqual 2.5
Bare Nuclei lessOrEqual 5.5
class equal 2

Uniformity of Cell Size lessOrEqual 2.5
Bare Nuclei greaterThan 5.5
class equal 4


text:
Q: Convert SOAP XML response to PHP object or array I have found this piece of PHP code:
<?php

$client = new SoapClient("http://localhost/code/soap.wsdl");

// Soap call with HelloWorld() method
$something =  $client->HelloWorld(array('option1' => 'attribute1'));

// Convert object to array
$array = (array)$something;

I just want to know where soap.wsdl resides or from where we can download soap.wsdl file for PHP.

A: The location of the WSDL-file is going to depend on the SOAP API you're calling. Check their documentation.
The example code you provided of implies they're working locally, and you're hosting the WSDL on your own, local machine.
Research Edit
Apparently you can use the PHP soap client in non-WSDL mode. This is accomplished by passing in null as the param instead of the location of the wsdl file.
Also relevant, is this other SO result on non-WSDL mode


text:
Q: Rearrange values position in chordDiagram() in R I have the following correlation values in R namely ``dat` as follows:
dat <- as.matrix(cbind(c(1.0000000, 0.5161944, 0.5190630, 0.3717464, 0.5719125),
                       c(0.5161944, 1.0000000, 0.2549985, 0.8469740, 0.7761113),
                       c(0.5190630, 0.2549985, 1.0000000, 0.2130771, 0.2930945),
                       c(0.3717464, 0.8469740, 0.2130771, 1.0000000, 0.5652874),
                       c(0.5719125, 0.7761113, 0.2930945, 0.5652874, 1.0000000))
)
colnames(dat) <- c(paste0("X",1:ncol(dat)))
rownames(dat) <- c(paste0("X",1:ncol(dat)))
dat[lower.tri(dat)] <- 0

and I have created the following chord diagram:
circos.par(gap.degree = 0.8)
chordDiagram(dat, transparency = 0.5, scale = T, annotationTrack = c("name", "grid"))

for (i in 1:ncol(dat)) {
  circos.xaxis(sector.index = paste0("X", i),
               major.at = seq(0, 1, .25),
               minor.ticks = 0,
               labels.cex = .5)
}

which results in:
However, even though the values are represented in the plot in the correct colour, they are not placed in the correct position in the grid axis. For example the value between X3 and X4 is 0.21, but in the X4 is placed between [0.25-0.5) and in the X3 is placed between [0,0.25) but it should be closer to 0.25 and not 0 as it is displayed. How can I fix the positions??


text:
Q: How to invoke a function in child component from parent? So my parent component has a "Next" button. When I tap this "Next" button, I want this to invoke a function in the child that passes data to the global state. What's the best way to go about this? Here's some dummy code:
<Parent />

this.state{
  change: 'Two'
}

functionOne(){
  this.setState({
    change: 'One'
  })
}

render(){
  return(
    <View>
      <TouchableOpacity
        onPress={ () => this.functionOne() }>
      </TouchableOpacity>
    </View>
  )
}

<Child />

this.state {
  data1: "I"
  data2: "WANT"
  data3: "THIS"
}

thisOne(){
 this.props.toGlobal(this.state)
}

A: You can set a ref on the child component and call the function from the parent.
// Parent
render(){
  return(
    <View>
      <TouchableOpacity
        onPress={ () => this.child.functionOne() }>
      </TouchableOpacity>
      <Child ref={child => this.child = child} />
    </View>
  )
}

A: You should pass down the handler to the child and then call it on the parent with whatever values you wish to update as parameters.
Example:
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      change: 'Two'
    };

    this.toGlobal = this.toGlobal.bind(this);
  }

  toGlobal(values) {
    // update global state with value
  }

  render() {
    return(
      <Child
        toGlobal={this.toGlobal} />
    );
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state {
      data1: "I"
      data2: "WANT"
      data3: "THIS"
    };

    this.thisOne = this.thisOne.bind(this);
  }

  thisOne() {
    this.props.toGlobal(this.state);
  }

  render() {
    return (
      <div>
        <button
          onClick={this.thisOne} />
      </div>
    );
  }
}