text:
Q: Importing img Url from MongoDB using Mongoose doesn't work I'm trying to import img url from my database (mongodb) using mongoose, and display it with EJS, my problem is that I always get undefined.
The data I get when using findById is "item" =
[
    {
        _id: 5b809b2c74e2f54c20ae30da,
        brand: 'honda',
        model: 'cbr250r',
        price: 20000,
        amount: 20,
        img: 'https://news.maxabout.com/wp-content/uploads/2016/12/22.png',
        backImg: 'https://wallpapercave.com/wp/wp3065342.png',
        views: 1,
        desc: 'this is a bike description'
    }
]

and I'm trying getting my "backImg" using this path: "item[0].backImg". When I console.log it I get undefined. I also tried "item.backImg"
that's the route file which includes the function:
const router = require('express').Router();
const bodyParser=require('body-parser')
const urlencodedParser =bodyParser.urlencoded({extended:false})
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
const itemModel = require('../models/itemsModel')
const userModel = require('../models/userModel')

//items//
router.get('/:_id',(req,res)=>{
    console.log(req.params._id)
    let q = itemModel.find({_id:req.params._id})
    q.exec(function(err,item){
        if(err){
            console.log(err)
        } else {
            console.log(item)
            console.log(item[0].brand)
            console.log(item[0].backImg)
            console.log(item.backImg)
            res.render('./pages/items' , {item:item,user: req.user,} )
        }
    })
})

module.exports = router

A: I think it should be like this
..... // previous code
itemModel.findOne({_id:req.params._id})
.then((item)=>{
    if(!item){
        console.log("No record found");
    }
    console.log(item)
    console.log(item.brand)
    console.log(item.backImg)
})
.catch(err=>{
    console.log("Error",err)
})

Here you can see I have used the findOne method of mongoose that will give only 1 result (single object) from database.Also check if req.params._id is not undefined.If you have any queries let me know.

A: so its seems those field that was imported as undefiend werent added to the item schema so that was the problem


text:
Q: ¿Cómo agrupar el valor máximo de cada mes en MySQL? cree una vista que me muestra el total de las ventas de cada mes desde el el 2018 hasta la fecha la vista se llama "vista_suma_documentos" y es la siguiente:

necesito obtener el valor mas alto de cada mes, esto quiere decir que me muestre el valor mas alto de enero, el valor mas alto de febrero etc. mostrándome así 12 registros con su mes y año.
la consulta que tengo el la siguiente:
select max(documentos),fecha_documentos
from vista_suma_documentos
group by month(fecha_documentos)

el resultado entregado es el siguiente:

al verificar los valores están correctos pero las fechas que los acompañan no lo son ya que esos valores corresponden a otras fechas.
dejo una imagen de un resultado esperado como ejemplo mostrándome el valor mas alto de todos los enero, febrero, marzo etc.

la creación de la vista es la siguiente:
CREATE ALGORITHM = UNDEFINED DEFINER = root@localhost SQL SECURITY DEFINER VIEW vista_suma_documentos AS
    SELECT
    SUM(cargos.CAVALO) AS documentos, cargos.CAFECO AS fecha_documentos
    FROM cargos
    WHERE cargos.CATIPO <> '3'
    AND cargos.CAFECO BETWEEN '2018-01-01'
    AND CURRENT_TIMESTAMP()
    GROUP BY YEAR(cargos.CAFECO) , MONTH(cargos.CAFECO)

gracias por la ayuda de ante mano.

A: Ok, lo que quieres hacer parece que es esto:
SELECT YEAR(cargos.CAFECO) ejercicio,
    MONTH(cargos.CAFECO) mes,
    SUM(cargos.CAVALO) AS documentos,
    MAX(cargos.CAVALO) AS maximo_cargo
    FROM cargos
    WHERE cargos.CATIPO <> '3'
    AND cargos.CAFECO BETWEEN '2018-01-01'
    AND CURRENT_TIMESTAMP()
    GROUP BY 1,2;

La vista estaba truncando parte de la información que necesitabas, por eso te pedí el código que la generaba.
Mes con el valor más alto
Si lo que quieres es quedarte con el mes con el cargo más alto, puedes lograrlo así:
SELECT YEAR(cargos.CAFECO) ejercicio,
    MONTH(cargos.CAFECO) mes,
    SUM(cargos.CAVALO) AS documentos,
    MAX(cargos.CAVALO) AS maximo_cargo
    FROM cargos
    WHERE cargos.CATIPO <> '3'
    AND cargos.CAFECO BETWEEN '2018-01-01'
    AND CURRENT_TIMESTAMP()
    GROUP BY 1,2
    ORDER BY maximo_cargo DESC
    LIMIT 1;

En cambio, si necesitas el mes con mayor volúmen, ordena por documentos.
Monto más alto de cada mes
Si buscas el mejor resultado de cada mes, tendrías que hacer así:
SELECT mes,MAX(documentos) mejor_volumen_de_ese_mes,
    MAX(maximo_cargo) mejor_cargo_de_ese_mes
    FROM (
        SELECT YEAR(cargos.CAFECO) ejercicio,
            MONTH(cargos.CAFECO) mes,
            SUM(cargos.CAVALO) AS documentos,
            MAX(cargos.CAVALO) AS maximo_cargo
            FROM cargos
            WHERE cargos.CATIPO <> '3'
            AND cargos.CAFECO BETWEEN '2018-01-01'
            AND CURRENT_TIMESTAMP()
            GROUP BY 1,2
    ) c1 GROUP BY 1;

Ejercicio al que corresponde cada máximo
SELECT mes,ejercicio,documentos FROM (
    FROM (
        SELECT YEAR(cargos.CAFECO) ejercicio,
            MONTH(cargos.CAFECO) mes,
            SUM(cargos.CAVALO) AS documentos,
            MAX(cargos.CAVALO) AS maximo_cargo
            FROM cargos
            WHERE cargos.CATIPO <> '3'
            AND cargos.CAFECO BETWEEN '2018-01-01'
            AND CURRENT_TIMESTAMP()
            GROUP BY 1,2
    ) c1 JOIN (
        SELECT mes,MAX(documentos) documentos
            FROM (
                SELECT YEAR(cargos.CAFECO) ejercicio,
                    MONTH(cargos.CAFECO) mes,
                    SUM(cargos.CAVALO) AS documentos,
                    MAX(cargos.CAVALO) AS maximo_cargo
                    FROM cargos
                    WHERE cargos.CATIPO <> '3'
                    AND cargos.CAFECO BETWEEN '2018-01-01'
                    AND CURRENT_TIMESTAMP()
                    GROUP BY 1,2
            ) c1 GROUP BY 1
    ) c2 USING(mes,documentos);

Déjame cualquier duda en los comentarios.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redis Sentinel myid Does anyone know how redis sentinel determines the value for
myid in the config file?
I've created an image for deploying redis on my network but the Redis Sentinel values for myid are all duplicated, which is causing lots of log spam showing:

[991] 30 Nov 20:56:48.639 * -dup-sentinel master mymaster 10.254.18.162 6379 #duplicate of 10.254.18.160:26379 or e2aa60902f872679221db15c4b414c7d5b3eca7c
[991] 30 Nov 20:56:48.639 * +sentinel sentinel 10.254.18.160:26379 10.254.18.160 26379 @ mymaster 10.254.18.162 6379

Attempts at manually changing the value fail b/c the file rewrites itself with the old value.

A: Ok well what I had to do was stop redis-sentinel, delete most of the config, including the myid line, and then start redis-sentinel back up. It generated a new id.


text:
Q: How to store data from a GHashTable to a struct in C I'm trying to iterate over my hash table and store the key and value into an array of structures. I keep getting a segfault. I'm guessing is due to the pointer based struct.
I'm still confused when I should use pointers to structures, and array of structures.
Edit: Got it to work. See answer below.

A: #include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

typedef struct st {
    char *key;
    char *str;
    int len;
} MyStruct;

int z = 0;
static void hash2struct (gpointer key, gpointer value, gpointer data) {
    MyStruct **s = data;
    gchar *k = (gchar *) key;
    gchar *h = (gchar *) value;
    s[z]->key = strdup(k);
    s[z]->str =strdup(h);
    z++;
}

int main(int argc, char *argv[]){
    int i;

    GHashTable *hash = g_hash_table_new(g_str_hash, g_str_equal);

    g_hash_table_insert(hash, "Virginia", "Richmond");
    g_hash_table_insert(hash, "Texas", "Austin");
    g_hash_table_insert(hash, "Ohio", "Columbus");

    MyStruct **s = malloc(sizeof(MyStruct) * 3);
    for(i = 0; i < 3; i++) {
        s[i] = malloc(sizeof(MyStruct));
    }
    g_hash_table_foreach(hash, hash2struct, s);

    for(i = 0; i < 3; i++)
        printf("%s %s\n", s[i]->str, s[i]->key);

    for(i = 0; i < 3; i++) {
        free(s[i]->str);
        free(s[i]->key);
        free(s[i]);
    }
    free(s);
    g_hash_table_destroy(hash);
    return 0;
}


text:
Q: Contact physics Gap in SpriteKit (Swift) I am working on my first swift iOS sprite kit project but I've run into a problem that I just can't find a solution to. My goal is to have a ball land on a moving platform and the ball and platform both stop upon contact.
The issue I am running into is that there is consistently a gap between the platform and ball when the code recognizes they are in contact and makes them stop. See the attached photo:
Image Here
Ball:
//Ball Node
func createPlayer() -> SKNode {
    let playerNode = SKNode()
    playerNode.position = CGPoint(x: self.size.width / 2, y: self.size.height * 0.25)

    let sprite = SKSpriteNode(imageNamed: "ball")
    sprite.setScale(scaleFactor)

    playerNode.addChild(sprite)
    playerNode.physicsBody = SKPhysicsBody(circleOfRadius: sprite.size.width / 2)
    playerNode.physicsBody?.dynamic = false
    playerNode.physicsBody?.allowsRotation = false
    playerNode.physicsBody?.restitution = 0.0
    playerNode.physicsBody?.friction = 0.0
    playerNode.physicsBody?.angularDamping = 0.0
    playerNode.physicsBody?.linearDamping = 0.0
    playerNode.physicsBody?.usesPreciseCollisionDetection = true
    playerNode.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Player
    playerNode.physicsBody?.collisionBitMask = 0
    playerNode.physicsBody?.contactTestBitMask = CollisionCategoryBitmask.Platform | CollisionCategoryBitmask.Vortex

    return playerNode

Platform:
//Platform
sprite = SKSpriteNode(imageNamed: "platform")
let node = PlatformNode()
let thePosition = CGPoint(x: position.x * scaleFactor - (sprite.size.width / 1.999), y: position.y + (self.size.height * 0.50))
 sprite.setScale(scaleFactor)
 node.addChild(sprite)
node.physicsBody?.usesPreciseCollisionDetection = true
node.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size)
node.physicsBody?.dynamic = false
node.physicsBody?.categoryBitMask = CollisionCategoryBitmask.Platform
node.physicsBody?.collisionBitMask = 0
return node

didBeginContact:
func didBeginContact(contact: SKPhysicsContact) {
    var updateHUD = true
    maxPlayerY = Int(player.position.y)
    let whichNode = (contact.bodyA.node != player) ? contact.bodyA.node : contact.bodyB.node
    //If the ball is falling
    if player.physicsBody?.velocity.dy < 0 {
        let other = whichNode as! GameObjectNode

        //If the player hits the Platform
        if player.physicsBody?.velocity.dy < 0 && whichNode?.name == "NODE_PLATFORM" {

            let joint = SKPhysicsJointFixed.jointWithBodyA(player.physicsBody, bodyB:whichNode!.physicsBody, anchor:CGPoint(x: player.position.x, y: ballBottom))
            let moveScreen = SKAction.moveToY(-(player.position.y - 200), duration: 0.5)
            let moveVortex = SKAction.moveToY((player.position.y - scaleFactor*300), duration: 0.5)

                physicsWorld.addJoint(joint
                player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 0)
                player.physicsBody?.affectedByGravity = false
                }
            }
    }

A: I suspect you can resolve this issue by waiting until after the physics simulation has completed (for the current frame) before connecting the objects. One way to do that is to a set a flag when the ball is in contact with the platform in didBeginContact and then connect the two bodies with a joint in didSimulatePhysics.


text:
Q: How to bind the datacontext of a tabcontrol content to an instance of an viewmodel in a observablecollection I want to bind the content of my TabControl to an instance of my StepViewModel in a ObservableCollection Steps.
My ProcessViewModel:
pubic class ProcessViewModel : ViewModelBase
{
    public ObservableCollection<StepViewModel> Steps
    {
        get { return _steps; }
        set { _steps = value; OnPropertyChanged("Steps"); }
    }
    public StepViewModel SelectedStep
    {
        // like above...
    }
}

My StepViewModel (DataContext should be the StepVMs in Steps of ProcessVM):
public class StepViewModel : ViewModelBase
{
    public string Name { get {...} set {...} }
    public object Media { get {...} set {...} }
    //...
}

My TabControl (DataContext is ProcessViewModel):
<C1:C1TabControl
    ItemsSource="{Binding Steps}"
    SelectedItem="{Binding SelectedStep}"
    SelectionChanged="{tcSteps_OnSelectionChanged">
           <C1:C1TabControl.ContentTemplate>
                <DataTemplate>
                    <local:StepView
                        DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vmns:ProcessViewModel}}, Path=SelectedStep}"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch">
                    </local:StepView>
                </DataTemplate>
            </C1:C1TabControl.ContentTemplate>
</C1:C1TabControl>

The Compiler delivers the following output message:

"System.Windows.Data Error: 40 : BindingExpression path error:
  'SelectedStep' property not found on 'object' ''StepViewModel'
  (HashCode=32952144)'. BindingExpression:Path=SelectedStep;
  DataItem='StepViewModel' (HashCode=32952144); target element is
  'StepView' (Name='StepView'); target property is 'DataContext' (type
  'Object')"

Does anyone know how I can solve the?
Thanks!

A: It looks like there could be a few small issues with the RelativeSource on your DataContext binding for the StepView. Since the template is not part of the visual tree, I don't think you can use FindAncestor. You can use a StaticResource as a pointer to your main DataContext (eg http://www.codeproject.com/Articles/27432/Artificial-Inheritance-Contexts-in-WPF), but I think it might be simpler to just search by ElementName instead in this case. That method would look something like this:
Update your TabControl to have a name, so it is searchable in bindings by ElementName
<C1:C1TabControl
    x:Name="MyTabControl"
    ItemsSource="{Binding Steps}"
    SelectedItem="{Binding SelectedStep}"
    SelectionChanged="{tcSteps_OnSelectionChanged">

Update your StepView to look for the TabControl's DataContext by ElementName
    <local:StepView DataContext="{Binding ElementName=MyTabControl, Path=DataContext.SelectedStep}"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch">
    </local:StepView>


text:
Q: Why is my Xcode simulator just showing me a black screen? No scene delegate set? I've seen a similar question before but the post was very old and none of the answers worked for me. I am making a really simple code for cs50's mobile track which is just a tiny pokedex, but whenever I run my app simulator, I am met with a black screen instead of the app.
Here is what it says in the debugger if that helps: There is no scene delegate set. A scene delegate class must be specified to use a main storyboard file.
AppDelegate:
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

}

SceneDelegate:
import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }

}

info:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>$(PRODUCT_NAME)</string>
    <key>CFBundlePackageType</key>
    <string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>UIApplicationSceneManifest</key>
    <dict>
        <key>UIApplicationSupportsMultipleScenes</key>
        <false/>
        <key>UISceneConfigurations</key>
        <dict>
            <key>UIWindowSceneSessionRoleApplication</key>
            <array>
                <dict>
                    <key>UISceneConfigurationName</key>
                    <string>Default Configuration</string>
                    <key>UISceneDelegateClassName</key>
                    <string>$(PRODUCT_MODULE_NAME).SceneDelegate</string>
                    <key>UISceneStoryboardFile</key>
                    <string>Main</string>
                </dict>
            </array>
        </dict>
    </dict>
    <key>UILaunchStoryboardName</key>
    <string>LaunchScreen</string>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
        <string>UIInterfaceOrientationPortraitUpsideDown</string>
        <string>UIInterfaceOrientationLandscapeLeft</string>
        <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
</dict>
</plist>

A: It's the é in the name of your project. Don't do that.
Keep in mind that the project name is not user-facing. You can call the app by a name that has an é in it, but don't attempt to start a project with a name like that. Bad Things will happen (and you just encountered one of them).
I suggest that you just start all over. That will be easier than trying to rename the project and all that relates to it.


text:
Q: Proof that $\sum_{i=1}^\infty \mathbb{I}_{ \Gamma_i}$ is a Poisson Random Measure on $[0,\infty)$ For $X_i \sim \text{i.i.d}~ \text{expo(1)}$ defined on $E=[0,\infty)$, and $\Gamma_i = \sum_{i=1}^nX_i$. I want to show that $N=\sum_{i=1}^\infty \mathbb{I}_ {\Gamma_i} $ is a homogenous Poisson random measure (PRM).
For $k \ge 1$ and $A \in$Borel$(E)$, I want to solve:
$$
P(N(A)=k) =  P\left ( \sum_{i=k}^\infty \mathbb{I} \left ( \Gamma_i \in A \right )=k \right)
$$
where $\mathbb I$ is an indicator function.Im having trouble simplifying the inner probability involving the $\Gamma_i$ due to their dependence.
Update: Focusing on the distribution of $N_t = N([0,t])$, given by:
\begin{align*}
P(N([0,t]=k) &= P(X_1+X_2+...+X_{k+1}>t,X_1+X_2+...+X_{k}<t)\\
&=\int_{y=0}^t \frac{y^{k-1}}{(k-1)!}e^{-y} \int_{x=t-y}^\infty e^{-x}
\, \mathrm dx\, \mathrm dy\\
&= \int_{y=0}^t \frac{y^{k-1}}{(k-1)!}e^{-y} e^{-(t-y)}\, \mathrm dy\\
&= e^{-t}\int_{y=0}^t \frac{y^{k-1}}{(k-1)!}\, \mathrm dy\\
&=e^{-t}\frac{t^k}{k!}
\end{align*}
So $N_t \sim \text{Poi}(t-0 = t)$. Would this be enough to say that if we now look at any $[a,b]\in$Borel$(E)$, then we would have $N_{[a,b]} \sim \text{Poi}({b-a})$?


text:
Q: ODBC instant client install issue I am trying to install odbc for instant client 19_14. I have downloaded the necessary .exe files etc and saved them down to my C drive. I have then navigated to the directory:
C:\oracle\instantclient_19_14>

And I execute the following:
 C:\oracle\instantclient_19_14>odbc_install.exe

However I am getting the following error:
Couldn't find Oracle Instant Client in present directory.

Does anyone know why this is. I can see the odbc_install file in the folder, so its not clear why there is an error.

A: for Oracle client in Windows you need to define System Variable:
OCI_LIB32 -> C:\oracle\instantclient_19_14
and add to Path variable -> C:\oracle\instantclient_19_14
BR,
Ely


text:
Q: Which algorithm is best for Text Summarization? Cosine, Dice, Jaccard out of these algorithms which algorithm is best for Text Summarization?

A: None of them is an algorithm for text summarization at all.
They are similarity measures that can be applied for two texts.

A: Extractive summarization
Extractive summarization means identifying important sections of the text and generating them verbatim producing a subset of the sentences from the original text; while abstractive summarization reproduces important material in a new way after interpretation and examination of the text using advanced natural language techniques to generate a new shorter text that conveys the most critical information from the original one.
This is where the model identifies the important sentences and phrases from the original text and only outputs those.
Abstractive Summarization
Abstractive Summarization is more advanced and closer to human-like interpretation. Though it has more potential (and is generally more interesting for researchers and developers), so far the more traditional methods have proved to yield better results.
The model produces a completely different text that is shorter than the original, it generates new sentences in a new form, just like humans do. In this tutorial, we will use transformers for this approach.
reference_text = """Artificial intelligence (AI, also machine intelligence, MI) is intelligence demonstrated by machines, in contrast to the natural intelligence (NI) displayed by humans and other animals. In computer science AI research is defined as the study of "intelligent agents": any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals. Colloquially, the term "artificial intelligence" is applied when a machine mimics "cognitive" functions that humans associate with other human minds, such as "learning" and "problem solving". See glossary of artificial intelligence. The scope of AI is disputed: as machines become increasingly capable, tasks considered as requiring "intelligence" are often removed from the definition, a phenomenon known as the AI effect, leading to the quip "AI is whatever hasn't been done yet." For instance, optical character recognition is frequently excluded from "artificial intelligence", having become a routine technology. Capabilities generally classified as AI as of 2017 include successfully understanding human speech, competing at a high level in strategic game systems (such as chess and Go), autonomous cars, intelligent routing in content delivery networks, military simulations, and interpreting complex data, including images and videos. Artificial intelligence was founded as an academic discipline in 1956, and in the years since has experienced several waves of optimism, followed by disappointment and the loss of funding (known as an "AI winter"), followed by new approaches, success and renewed funding. For most of its history, AI research has been divided into subfields that often fail to communicate with each other. These sub-fields are based on technical considerations, such as particular goals (e.g. "robotics" or "machine learning"), the use of particular tools ("logic" or "neural networks"), or deep philosophical differences. Subfields have also been based on social factors (particular institutions or the work of particular researchers). The traditional problems (or goals) of AI research include reasoning, knowledge, planning, learning, natural language processing, perception and the ability to move and manipulate objects. General intelligence is among the field's long-term goals. Approaches include statistical methods, computational intelligence, and traditional symbolic AI. Many tools are used in AI, including versions of search and mathematical optimization, neural networks and methods based on statistics, probability and economics. The AI field draws upon computer science, mathematics, psychology, linguistics, philosophy and many others. The field was founded on the claim that human intelligence "can be so precisely described that a machine can be made to simulate it". This raises philosophical arguments about the nature of the mind and the ethics of creating artificial beings endowed with human-like intelligence, issues which have been explored by myth, fiction and philosophy since antiquity. Some people also consider AI to be a danger to humanity if it progresses unabatedly. Others believe that AI, unlike previous technological revolutions, will create a risk of mass unemployment. In the twenty-first century, AI techniques have experienced a resurgence following concurrent advances in computer power, large amounts of data, and theoretical understanding; and AI techniques have become an essential part of the technology industry, helping to solve many challenging problems in computer science."""

Abstractive Summarize
len(reference_text.split())
from transformers import pipeline
summarization = pipeline("summarization")
abstractve_summarization = summarization(reference_text)[0]["summary_text"]

Output
In computer science AI research is defined as the study of "intelligent agents" Colloquially, the term "artificial intelligence" is applied when a machine mimics "cognitive" functions that humans associate with other human minds, such as "learning" and "problem solving" Capabilities generally classified as AI as of 2017 include successfully understanding human speech, competing at a high level in strategic game systems (such as chess and Go)

Extractive summarization
from sumy.parsers.plaintext import PlaintextParser
from sumy.nlp.tokenizers import Tokenizer
from sumy.summarizers.lex_rank import LexRankSummarizer
parser = PlaintextParser.from_string(reference_text, Tokenizer("english"))
summarizer = LexRankSummarizer()
extractve_summarization  = summarizer(parser.document,2)
extractve_summarization = ' '.join([str(s) for s in list(extractve_summarization)])

Extractive Output
Colloquially, the term "artificial intelligence" is often used to describe machines that mimic "cognitive" functions that humans associate with the human mind, such as "learning" and "problem solving".As machines become increasingly capable, tasks considered to require "intelligence" are often removed from the definition of AI, a phenomenon known as the AI effect. Sub-fields have also been based on social factors (particular institutions or the work of particular researchers).The traditional problems (or goals) of AI research include reasoning, knowledge representation, planning, learning, natural language processing, perception and the ability to move and manipulate objects.

A: seq2seq deep learning models are mostly used for this case,
this is a blog series that talks in much detail from the very beginning of how seq2seq works till reaching the newest research approaches
Also this repo collects multiple implementations on building a text summarization model, it runs these models on google colab, and hosts the data on google drive, so no matter how powerful your computer is, you can use google colab which is a free system to train your deep models on
If you like to see the text summarization in action, you can use this free api.
I truly hope this helps


text:
Q: Is 'colorblind' the best word for people with color perception deficiencies? I'm creating an application that has a checkbox to assist colorblind users. I'm not so fond of the term because it isn't accurate, but at the same time I don't want to seem overtly politically correct.
A couple of options I'm juggling right now:

*

*Colorblind assistance

*Reduced color perception assistance

*Color perception assistance

*Problems perceiving colors?

A: Don't worry too much about the political correctness aspect. People who have the disability know it, and are typically grateful for any software that acknowledges their condition and provides assistance. (I speak from experience: I have close relatives who have the condition, and have known many others; I also work as a UI developer, and as such I am required to make sure color palettes accommodate those with differing perceptions of color.)
As you know, there are different types of color-blindness: monochromacy, dichromacy, and trichromacy (there are other terms, such as deuteranopia, tritanopia, etc., which cover multiple ranges of color-perception ability). Check which you mean to correct for, because they can be vastly different. At least look at the article on Wikipedia, from which here are a few excerpts:

Color blindness or color vision deficiency is the inability or decreased ability to see color, or perceive color differences, under lighting conditions when color vision is not normally impaired. "Color blind" is a term of art; there is no actual blindness but there is a fault in the development of one or more sets of retinal cones that perceive color in light and transmit that information to the optic nerve.
...
Color blindness is usually classed as a mild disability but there are situations where color blind individuals can have an advantage over those with normal color vision. Some studies conclude that color blind individuals are better at penetrating certain color camouflages; this may be an evolutionary explanation for the surprisingly high frequency of congenital red–green color blindness.

There are various resources available to assist you in developing for color deficiencies. Look at a color simulator or two so you can get better acquainted with the types and how to correct for them. There are also plugins for Photoshop that will render your image as the various classes of color-blind individuals will see them.
My suggestion would be to offer color correction mechanisms and label them by what type of color deficiency they assist with: red-green deficiency, blue-yellow deficiency, etc.

A: Colorblind Assist is perfectly appropriate. Some video games like Call of Duty: Modern Warfare 3 have also Colorblind Assist option for colorblinds.
Side note: 8% of men and 0.5% of women suffer from color blindness.

A: People who are colorblind are chromodysoptic. Sorry that's of no practical use though.
[Edit: Be mindful that this is intended as a neologism, though a quite good one]


text:
Q: android open gallery via intent ACTION_PICK vs ACTION_GET_CONTENT in my app i would like to have the user choose an image from the gallery and retrieve the result (thumbnail + full image uri). i would also like the user to be able to choose which gallery app to open (i.e. default gallery app or some other gallery app).
initially, according to this guide by google i copied and pasted this code:
public void selectImage() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*");
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, REQUEST_IMAGE_GET);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
        Bitmap thumbnail = data.getParcelable("data");
        Uri fullPhotoUri = data.getData();
        // Do work with photo saved at fullPhotoUri
        ...
    }
}

while it does get me the thumbnail and the full Uri in onActivityResult(...), the problem is that it does not open a chooser for the user to select which gallery app to use and instead it opens this thing (see images below), which i assume is a default "image-chooser" thing where you could select another app via a menu.

i feel it's silly that the user would have to open this default "image chooser" first and once they are already in an "image chooser", select the gallery app that they actually want to use (sure, the user could just choose the image from this thing, but i want to give them a convenient choice).
so i changed my code to this and it does indeed display a proper chooser for the user and he can go straight to hes favorite gallery app:
Intent intent = new Intent(Intent.ACTION_PICK,
                                   MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");

        if (intent.resolveActivity(getActivity().getPackageManager()) != null)
        {
            startActivityForResult(intent, Utils.REQUEST_CODE_OPEN_GALLERY);
        }

however now i have a new problem: in onActivityResult(...) the line data.getParcelable("data"); returns null. in other words, i don't get back a thumbnail.
i also tried
Bundle extras = data.getExtras();
                Bitmap thumbnail = (Bitmap) extras.get("data");

but "extras" is null.
is it possible to have a proper "app chooser" AND get back a thumbnail?

A:
however now i have a new problem: in onActivityResult(...) the line data.getParcelable("data"); returns null. in other words, i don't get back a thumbnail.

You do not get that from ACTION_GET_CONTENT, either. You can tell this by reading the documentation for ACTION_GET_CONTENT. It is certainly possible that there are some buggy ACTION_GET_CONTENT activities that happen to return a thumbnail Bitmap in a "data" extra, but you should not assume that any user will have such a buggy ACTION_GET_CONTENT activity, let alone choose it. Besides, ACTION_GET_CONTENT is not limited to images; what would a "thumbnail" be of application/json or text/csv be?
Likewise, if you read the documentation for ACTION_PICK, you will see that there is no discussion of a thumbnail.

is it possible to have a proper "app chooser" AND get back a thumbnail?

No, insofar as you do not get a thumbnail back from anything except ACTION_IMAGE_CAPTURE, and that is for taking photos.


text:
Q: Sorting with a predefined list in R I am trying to sort this dataframe:
 Age  grade name
 21.0   6   John
 21.0   6   Paul
 22.8   4   Jake

With the help of a list of names:
Paul, Jake, John

What is the most simple way to do it?

A: Data generation:
txt <-
"Age  grade name
21.0   6   John
21.0   6   Paul
22.8   4   Jake "
df <- read.table(text=txt, header=T)

In order to support custom sorting you can convert column to factor with specified levels:
df$name <- factor(df$name, levels=c("Paul", "Jake", "John"))

Now ordering df[order(df$name),] gives:
   Age grade name
2 21.0     6 Paul
3 22.8     4 Jake
1 21.0     6 John


text:
Q: Rails 4 - NoMethodError I am using the PaperClip, AWS, and s3_direct_upload gems to upload simple images.  I am following this tutorial here: http://blog.littleblimp.com/post/53942611764/direct-uploads-to-s3-with-rails-paperclip-and
The file is uploaded successfully to S3, but during post-processing, I get the following error:
  Completed 500 Internal Server Error in 973ms

  NoMethodError (undefined method `upload_file_name=' for #<Choice:0x007f9ea60e02d0>):
   app/models/choice.rb:60:in `set_upload_attributes'
   app/controllers/choices_controller.rb:24:in `create'

Here is what my model ("Choice") looks like, where upload_file_name should be defined: https://gist.github.com/dodinas/7237377
Any ideas on what I am doing wrong here?  Thanks very much!

A: Did you run your migrations. You would get that error if the column doesnt exist on the table in the database.


text:
Q: perl: function that gives nonzero integers between 1 and $input Im looking for (how to make?) a function (module?) that for
 my $scalar = 16;
 return function ($scalar);

gives
 @return = ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 );

That is, gives the non-zero integers between 1 and $scalar.
It's ok to assume $scalar is a big number, but im not particularly searching for a super optimal solution.

A: The Range Operator .. returns a list which matches exactly what you want.
To create a list from 1 to $x, the syntax is just 1 .. $x
To assign that to an array variable, @array = 1 .. $x;

A: [1..16]
creates an array reference
1..16 creates a list.
Try this source
use Data::Dumper;
$c = [1..16];
@d = 1..16;
print Dumper $c;
print Dumper \@d;

A: sub getvalue {
        my @array1 = 1..$_[0];

        return (@array1);
    }

else
sub getvalue {
            return ( 1..$_[0]);
        }

refer this too know more about range operator
http://www.perlmonks.org/?node_id=377450

A: What happens when you want all integers between 1 and 1_000_000_000? You wouldn't want to create an array that big even if your computer has enough memory.
#!/usr/bin/env perl

use strict;
use warnings;

sub make_lazy_increasing_sequence {
    my ($current, $end) = map int, @_;
    return sub {
        return if $current > $end;
        return $current++;
    }
}

my $from_1_to_5 = make_lazy_increasing_sequence(1, 5);
my @others;

while (defined(my $i = $from_1_to_5->())) {
    push @others, make_lazy_increasing_sequence($i, 10_000);
}

for (1 .. 10) { # perl makes sure this range is lazy
    print join(',', map $_->(), @others), "\n";
}

print $others[-1]->(), "\n";

Output:
1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
4,5,6,7,8
5,6,7,8,9
6,7,8,9,10
7,8,9,10,11
8,9,10,11,12
9,10,11,12,13
10,11,12,13,14
15


text:
Q: $\tau (x) = 2016$ and for least $x = a \times b^2$ find $b$.
$\tau(x) = 2016$. For the least value $x$ such that $x = a \times b^2$ and $a$ has no square divisors in it, find the value of $b$.
  [ $\tau (n) = \text{number of divisors of $n$}.$

This seems a quite easy problem. If $a$ and $b$ was prime then I would have solved it immediately. But they are not prime. So, I can't find a way to start with.
Source: BdMO 2016 question set 5 problem 8 (Higher Secondary).

A: $$x=p_1p_2p_3\cdots p_nq_1^{2\alpha_1}q_2^{2\alpha}\cdots q_m^{2\alpha_m}$$
$$\tau(x)=(1+1)^n(2\alpha_1+1)(2\alpha_2+1)\cdots (2\alpha_m+1)$$
Since  $2016=2^5\cdot3^2\cdot7$ we have
$$n=5,\space \alpha_1=1,\space\alpha_2=1,\space \alpha_3=3$$
All number of the form $x=p_1p_2p_3p_4p_5 q_1^2q_2^2q_3^6$ where the primes are distinct satisfies $\tau(x)=2016$.
If we want to have a minimum $x$ we must have
$$x=2^6\cdot3^2\cdot5^2\cdot 7\cdot 11\cdot 13\cdot 17\cdot 19$$ The corresponding value of $b$ is $$b=2^3\cdot3\cdot5=\color{red}{120}$$


text:
Q: Querying rails active record based on jsonb column I have record named User which is having a column called attrs.
The attrs is a jsonb column. The record looks like below:
I am posting as_json record of a  User.
{
  "id"=>uuid1,
  "profile_id"=>uuid2,
  "campaign_id"=>uuid3,
  "asset_id"=>uuid4,
  "brand_id"=>"5",
  "region"=>"Non-EU",
  "attrs"=>{
    uuid5=>{
      "label"=>"Email",
      "value"=>"example@test.com.tw"
    },
    uuid6=>{
      "label"=>"Last Name ",
      "value"=>"Yang"
    }
  }
}

I want to query The User active record based on
"label"=>"Email","value"=>"example@test.com.tw".
How can I do this?

A: Try,
User.where("settings @> ?", {uuid5: {label: 'Email', value: 'example@test.com.tw'}}.to_json)

For more reference see..
https://nandovieira.com/using-postgresql-and-jsonb-with-ruby-on-rails

A: Thanks to a_horse_with_no_name answer here is a raw sql version:
select u.*
from users u
where exists (select *
              from jsonb_each(u.attrs) as t(uid,entry)
              where t.entry ->> 'label' = 'Email'
                and t.entry ->> 'value' = 'example@test.com.tw')

And here is AR version:
User.find_by_sql(["
  select u.*
  from users u
  where exists (select *
                from jsonb_each(u.attrs) as t(uid,entry)
                where t.entry ->> 'label' = ?
                  and t.entry ->> 'value' = ?)
  ", 'Email', 'example@test.com.tw'])

You can move it to model scope or method. Or to separate query object.
It relies on postgresql jsonb_each method. I just noticed that you did not specify your database
Ref https://stackoverflow.com/a/55512200/4950680


text:
Q: timestamp from a txt file into an array I have a txt file with the following structure:
"YYYY/MM/DD HH:MM:SS.SSS val1 val2 val3 val4 val5'

The first line look like:
"2015/02/18 01:05:46.004   13.737306807  100.526088432   -22.2937   2   5"

I am having trouble to put the time stamp into the array. The time values are used to compare data with same timestamp from different files, parse the data for a specific time interval, and plotting purposes.
This is what I have right now ... except the time information:
dt=np.dtype([('lat', float), ('lon', float), ('height', float), ('Q', int), ('ns', int)]
a=np.loadtxt('tmp.pos', dt)

Any suggestion how to extent the dt to include the date and the time columns? or Is there a better way than using loadtext from numpy?
An example of the file can be found here: https://www.dropbox.com/s/j69l8oeqdm73q8y/tmp.pos
Edit 1
It turns out that the numpy.loadtxt takes a parameter called converters that may does the job:
a = np.loadtxt(fname='tmp.pos', converters={0: strpdate2num('%Y/%m/%d'), 1: strpdate2num('%H:%M:%S.%f')})

This means that the first two columns of a are 'date' and 'time' expressed as floats. To get back the time string, I can do something like this (though perhaps a bit clumsy):
In [441]: [datetime.strptime(num2date(a[i,0]).strftime('%Y-%m-%d')+num2date(a[i,1]).strftime('%H:%M:%S.%f'), '%Y-%m-%d%H:%M:%S.%f') for i in range(len(a[:,0]))]

which gives:
Out[441]: [datetime.datetime(2015, 2, 18, 1, 5, 46)]

However, the decimal part of the seconds are not preserved. What I am doing wrong?

A: If this is coming from a text file, it may be simpler to parse this as text unless you want it all to end up in a numpy array. For example:
>>> my_line = "2015/02/18 01:05:46.004   13.737306807  100.526088432   -22.2937   2   5"
>>> datestamp, timestamp, val1, val2, val3, val4, val5 = [v.strip() for v in my_line.split()]
>>> datestamp
'2015/02/18'
>>> timestamp
'01:05:46.004'

So if you want to iterate over a file of these lines and obtain a native datetime object for each ine:
from datetime import datetime
with open('path_to_file', 'r') as my_file:
    for line in my_file:
        d_stamp, t_stamp, val1, val2, val3, val4, val5 = [v.strip() for v in my_line.split()]
        dt_obj = datetime.strptime(' '.join([d_stamp, t_stamp]), '%Y/%m/%d %H:%M:%S.%f')

A: Better convert the time string in to timeStamp and pass the value as integer format. Integer will speed up your comparisons as well.
import time
dt, ts = "2015/02/18 01:05:46.004".split()
year,mon,day = [int(d) for d in dt.split('/')]
hrs,mins,secs = [int(float(d)) for d in ts.split(':')]
timeStamp = time.mktime((year,mon,day,hrs,mins,secs,0,0,time.localtime()[8]))

A: Pandas is supposed to be good at this sort of thing. I'm no expert and had some trouble with the parse_date functionality of read_csv but the following seems to work reasonably well and fast:
import pandas as pd

names = ('date', 'time', 'lat', 'lon', 'height', 'Q', 'ns')
format = '%Y/%m/%d%H:%M:%S.%f'
df = pd.read_csv('tmp.pos', delim_whitespace=True, names=names)
df['datetime'] = pd.to_datetime(df['date'] + df['time'], format=format)

If you want to select data based on time stamps, you can set it as the index of the dataframe:
df.index = pd.to_datetime(df['date'] + df['time'], format=format)
print df['2015-02-18 2:30:00':'2015-02-18 2:30:10']

You can also set the time column as the index, but it seems directly slicing with only time is not supported:
format = '%H:%M:%S.%f'
df.index = pd.to_datetime(df['time'], format=format)
print df['2:30:00':'2:30:10']  # prints empty DataFrame

But you can use the following:
print df.between_time('2:30:00','2:30:10')


text:
Q: Very fast document similarity I am trying to determine document similarity between a single document and each of a large number of documents (n ~= 1 million) as quickly as possible.  More specifically, the documents I'm comparing are e-mails; they are grouped (i.e., there are folders or tags) and I'd like to determine which group is most appropriate for a new e-mail.  Fast performance is critical.
My a priori assumption is that the cosine similarity between term vectors is appropriate for this application; please comment on whether this is a good measure to use or not!
I have already taken into account the following possibilities for speeding up performance:

*

*Pre-normalize all the term vectors

*Calculate a term vector for each group (n ~= 10,000) rather than each e-mail (n ~= 1,000,000); this would probably be acceptable for my application, but if you can think of a reason not to do it, let me know!
I have a few questions:

*

*If a new e-mail has a new term never before seen in any of the previous e-mails, does that mean I need to re-compute all of my term vectors? This seems expensive.

*Is there some clever way to only consider vectors which are likely to be close to the query document?

*Is there some way to be more frugal about the amount of memory I'm using for all these vectors?
Thanks!

A: Use Bayesian filtering. The link provided refers to spam filtering, but you can adapt the algorithm pretty easily to multiple categories/tags.
There are lots of good SO question about Bayesian filtering, too.


text:
Q: Why are SQL fields lengths always (2^n)-1 unless less than 127? A lot of Database schemas seem to follow the following standard:
(2^n)-1 for large fields:
varchar(511)
varchar(255)
varchar(127)

...then (2^n) for smaller ones
varchar(64)
varchar(32)
varchar(16)
varchar(8)

I understand why numbers of (2^n)-1 are used, what I don't understand is why it is not necessary to continue the trend down to the small fields.
E.g.
varchar(63)
varchar(31)
varchar(15)
varchar(7)

Is there a reason for this or is it just that the returns have diminished too far?

A: I think it's just programmers picking a number out of the air when it doesn't really matter.
If you had to put a limit on "notes" field for example a non programmer would probably pick 100 or 200 characters as a round number whereas a programmer might think of 127 or 255 as a round number.

A: I can't say as I've seen the "-1" trend used differently for smaller / larger fields. However I think its all nothing more than developer/dba OCD. Always wanting "round" numbers when they should really be making field length decisions based on business rules rather than "prettiness"

A: Not only have the returns diminished, but if you set string types with arbitrary limits you're much more likely to cause a problem than solve one.
If it's really a business constraint, then use TEXT type (or similar) and a CHECK constraint on the length, and pick the number according to the business constraint you're trying to enforce.
The DBMS will probably implement the storage for the TEXT type identically to varchar(x) anyway. If it doesn't, and you really care, you should investigate the internal storage strategies of your particular system, and consider whether there's any benefit to varchar or not.

A: I remember the old times, when using 2^n Length was better vor alignment of blocks on disk or memory.
Aligned block were faster.
Today "Block" sizes are bigger and memory and disk are fast enough to ignore the alignment,
exept for very large blocks that ist. (Whatever "very large" means today....)
Nowadays it is just traditional to do so.
And another reason my be the famous saying:
There are only 10 type of people: Those who can binary and the others.
And 2^n -1 are candidates for mersenne primes. so its geeky too...

A: Actually, that'S the first time I heard of such a "trend". My varchar-fields are always as long as I need them to be.
I would say that there's no particular reason behind it. Just the preference of the developer.

A: I can not imagine for a moment why they are sizing the fields that way on either count 2^N or 2^N-1. From a SQL Server perspective,  it sounds more like a misconception over how SQL is storing that data at the page level than a specific reason.
I would pay more attention to the types, potential off page storage (SLoB / LoB) and rows/page + meeting the business needs with sizing, than a formula based on using 2^N etc


text:
Q: Custom views for errors in CakePHP 2.1 I'm looking to create custom views for errors in CakePHP 2.1
I have been reading the following question here: CakePHP 2.0 - How to make custom error pages?
BUT there are somethings that do not work as expected!
1.) Exceptions and errors do not seem to be the same thing, as if I go to a bogus url I get the built in 404 page but if I manually do a notfound exception in the controller it will call the custom view... Why is this? I thought all errors in Cake went through the exceptions?
2.) I'm trying to render a view rather than ACTUALLY redirect the user...
so for example:
App::uses('ExceptionRenderer', 'Error');

class AppExceptionRenderer extends ExceptionRenderer {
    public function notFound($error) {
        $this->controller->redirect(array('controller' => 'errors', 'action' => 'error404'));
    }
}

instead of that redirect I'm trying:
$this->controller->layout = null;
$this->controller->render('/Errors/error404');

but all I end up with is a blank page... Why is this? And this only happens when doing manual exceptions?
Can anyone answer these two questions please? Thanks

A: I've finally managed to get this figured out! Looking at the code from github, I've managed to get it working. Here's my AppExceptionRenderer.php:
App::uses('ExceptionRenderer', 'Error');

class AppExceptionRenderer extends ExceptionRenderer {
    public function missingController($error) {
        $this->controller->render('/Errors/error404', 'layout');
        $this->controller->response->send();
    }

    public function missingAction($error) {
        $this->missingController($error);
    }
}

If you want to call your controller callbacks you'll have to do something like this as well before beforeFilter():
$this->controller->beforeFilter();

That $this->controller->response->send(); line is the kicker. Hopefully this works for you!

A: This is simple,
public function notFound($error) {
    $this->_outputMessage('error404');
}

That's all what you need to do

A: Simply:
throw new NotFoundException;

See the example code in the documentation about "Built in Exceptions".
App::uses('ExceptionRenderer', 'Error'); should not be required.
For an individual view edit View/Errors/error400.ctp.


text:
Q: Truncated incorrect DOUBLE value mysql error I want to delete multiple rows with checkboxes, php and sql, and here is my code for that:
<?php
include_once("../../files/connect.php");
if(isset($_POST['val']))
{
    $p = &$_POST['val'];
    foreach($p as &$v)
    {
        $v = "'". mysqli_escape_string($kapcs, $v) ."'";
    }
    $values = '('.implode(',',$p).')';
    $sql = "DELETE FROM elony WHERE elony_id IN $values";

    print_r($sql);

    mysqli_query($kapcs, $sql) or die("SQL ERROR - " . mysqli_error($kapcs));

    echo 'A kijelölt sorok törölve lettek az adatbázisból.';
}
else
{
    exit("Nem jelölt ki egyetlen sort sem.");
}
?>

My problem is, that i always get this error: )SQL ERROR - Truncated incorrect DOUBLE value: 'on'
If i echo out my query, it looks like: DELETE FROM elony WHERE elony_id IN ('on','3','4')
Whats that 'on'? How does it get into the query?


text:
Q: PHP - MySQL results to JSON I'm trying to understand how to convert MySQL results to a JSON format so that I can then use this JSON later on with Javascript to build a HTML table. However my code just produces lot's of null values and I don't yet understand why.
$result = mysqli_query($con, "SELECT * FROM Customers");

$test = json_encode($result);

print $test;

Output:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}

I have, for example, fields such as "CustomerID" and "Name", and even they don't show up in the JSON result.
What am I doing wrong?
Thanks

A: $result = mysqli_query($con, "SELECT * FROM Customers");
while($row = mysqli_fetch_assoc($result))
    $test[] = $row;
print json_encode($test);


text:
Q: jQuery slider fails to load first image I'm having problems with my slider when it comes to loading first page. When i'm using the "left" or "right" arrow under the images and then go back to first page everything is working. Got no idea where can i fix it.
http://fiddle.jshell.net/f7770oLf/1/
And actually i'm not sure if it's because of CSS or jQuery..

A: You override the .slide .active-slides visibility property by defining .slide as hidden afterwords. This makes the first slide invisible, since there's no jQuery call to make it visible. Change:
.active-slide
{
  display: block;
}

.slider
{
  margin-top: 25px;
  width: 100%;
  height: 669px;
}

.slide
{
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

So that .active-slide is after .slide:
.slider
{
  margin-top: 25px;
  width: 100%;
  height: 669px;
}

.slide
{
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.active-slide
{
  display: block;
}

Fiddle.

A: CSS loads in the order it is coded.  You are overwriting your .active-slide with the .slide class which disables the display: block; you're looking for.  To make it all work, move:
.active-slide
{
    display: block;
}

below
.slide
{
    display: none;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}


text:
Q: Is there a way to include a fragment identifier when using Asp.Net MVC ActionLink, RedirectToAction, etc.? I want some links to include a fragment identifier. Like some of the URLs on this site:
Debugging: IE6 + SSL + AJAX + post form = 404 error#5626
Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?

A: We're looking at including support for this in our next release.

A: In MVC3 (and possibly earlier I haven't checked), you can use UrlHelper.GenerateUrl passing in the fragment parameter. Here's a helper method I use to wrap the functionalityL
public static string Action(this UrlHelper url, string actionName, string controllerName, string fragment, object routeValues)
{
    return UrlHelper.GenerateUrl(
        routeName: null,
        actionName: actionName,
        controllerName: controllerName,
        routeValues: new System.Web.Routing.RouteValueDictionary(routeValues),
        fragment: fragment,
        protocol: null,
        hostName: null,
        routeCollection: url.RouteCollection,
        requestContext: url.RequestContext,
        includeImplicitMvcValues: true /*helps fill in the nulls above*/
    );
}

A: @Dominic,
I'm almost positive that putting that in the route will cause routing issues.
@Ricky,
Until MVC has support for this, you can be a little more "old school" about how you make your routes. For example, you can convert:
<%= Html.ActionLink("Home", "Index") %>

into:
<a href='<%= Url.Action("Index") %>#2345'>Home

Or you can write your own helper that does essentially the same thing.

A: As Brad Wilson wrote, you can build your own link in your views by simply concatenating strings. But to append a fragment name to a redirect generated via RedirectToAction (or similar) you'll need something like this:
public class RedirectToRouteResultEx : RedirectToRouteResult {

    public RedirectToRouteResultEx(RouteValueDictionary values)
        : base(values) {
    }

    public RedirectToRouteResultEx(string routeName, RouteValueDictionary values)
        : base(routeName, values) {
    }

    public override void ExecuteResult(ControllerContext context) {
        var destination = new StringBuilder();

        var helper = new UrlHelper(context.RequestContext);
        destination.Append(helper.RouteUrl(RouteName, RouteValues));

        //Add href fragment if set
        if (!string.IsNullOrEmpty(Fragment)) {
            destination.AppendFormat("#{0}", Fragment);
        }

        context.HttpContext.Response.Redirect(destination.ToString(), false);
    }

    public string Fragment { get; set; }
}

public static class RedirectToRouteResultExtensions {
    public static RedirectToRouteResultEx AddFragment(this RedirectToRouteResult result, string fragment) {
        return new RedirectToRouteResultEx(result.RouteName, result.RouteValues) {
            Fragment = fragment
        };
    }
}

And then, in your controller, you'd call:
return RedirectToAction("MyAction", "MyController")
       .AddFragment("fragment-name");

That should generate the URL correctly.

A: The short answer is: No. In ASP.NET MVC Preview 3 there's no first-class way for including an anchor in an action link. Unlike Rails' url_for :anchor, UrlHelper.GenerateUrl (and ActionLink, RedirectToAction and so on which use it) don't have a magic property name that lets you encode an anchor.
As you point out, you could roll your own that does. This is probably the cleanest solution.
Hackily, you could just include an anchor in a route and specify the value in your parameters hash:
routes.MapRoute("WithTarget", "{controller}/{action}/{id}#{target}");
...
<%= Html.ActionLink("Home", "Index", new { target = "foo" })%>

This will generate a URL like /Home/Index/#foo. Unfortunately this doesn't play well with URL parameters, which appear at the end of the URL. So this hack is only workable in really simple circumstances where all of your parameters appear as URL path components.

A: This is a client side solution but if you have jquery available you can do something like this.

A: Fragment identifiers are supported in MVC 5. See ActionLink's overloads at https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx and https://msdn.microsoft.com/en-us/library/dd492938(v=vs.118).aspx.


text:
Q: How to delete all variables after finishing the execution in Python GUI? My GUI program which is written by PyQt5, has 4 tabs which I run the other tab after finishing the current tab. For example execute Tab1 and after saving the results i go to second tab and run that tab. My question is that after finishing the execution of the current tab, how can i delete all variables which i have created during the execution of this tab. I mean deleting variables from the RAM.
Does using gc.collect at the end of that tab remove the variables?
Any answer would be very helpful for me.

A: You can try del statement

Deletion of a name removes the binding of that name from the local or
global namespace, depending on whether the name occurs in a global
statement in the same code block. If the name is unbound, a NameError
exception will be raised.

a = 1
b = 2
print(a)
print(b)
del a, b
print(b)

# NameError: name 'b' is not defined

A: I don't think there's a way to delete all of them built-in so I would add them to a var list when declaring them and delete all of them at once when ready.
    varlist = []

    myvar1 = 'string'
    varlist.append(myvar1)

    myvar2 = 123
    varlist.append(myvar2)

    for var in varlist:
        del var


text:
Q: browserify-shim Sortable global not being recognized by react-sortable-mixin I have a problem where react-sortable-mixin is not respecting the browserify-shim global:Sortable declaration in my package.json file thus causing the Sortable module to be packaged up in my bundle. I have run into a similar problem with other modules so it may very well be a config problem on my part. I have created a small test package that simply requires React and react-sortbable-mixin in order to demonstrate the problem:
package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "Just a test",
  "main": "index.js",
  "dependencies": {
    "react": "^0.14.8",
    "sortablejs": "^1.4.2"
  },
  "devDependencies": {
    "browserify-shim": "^3.8.12"
  },
  "browserify": {
      "transform": [
          "browserify-shim"
      ]
  },
  "browserify-shim": {
    "react": "global:React",
    "sortablejs": "global:Sortable",
    "sortablejs/react-sortable-mixin": {
      "depends": "sortablejs:Sortable"
    }
  }
}

index.js
"use strict";
var React = require('react');
var SortableMixin = require('sortablejs/react-sortable-mixin');

react-sortable-mixin.js (Just the first part of the module...)
(function (factory) {
'use strict';

if (typeof module != 'undefined' && typeof module.exports != 'undefined') {
    module.exports = factory(require('./Sortable'));
}
else if (typeof define === 'function' && define.amd) {
    define(['./Sortable'], factory);
}
else {
    /* jshint sub:true */
    window['SortableMixin'] = factory(Sortable);
}
})(function (/** Sortable */Sortable) { ...

Here is the diagnostic output from browserify:
% BROWSERIFYSHIM_DIAGNOSTICS=1 browserify index.js -t browserify-shim -o bundle.js

{ file: '/home/jlafosse/test/index.js',
  info:
   { package_json: '/home/jlafosse/test/package.json',
     packageDir: '/home/jlafosse/test',
     shim: undefined,
     exposeGlobals: { react: 'React', sortablejs: 'Sortable' },
     browser: undefined,
     'browserify-shim':
      { react: 'global:React',
        sortablejs: 'global:Sortable',
        'sortablejs/react-sortable-mixin': { depends: 'sortablejs:Sortable' } },
     dependencies: { react: '^0.14.8', sortablejs: '^1.4.2' } },
  messages:
   [ 'Resolved "sortablejs/react-sortable-mixin" found in package.json to "/home/jlafosse/test/sortablejs/react-sortable-mixin"',
     'Found depends "sortablejs" as an installed dependency of the package',
     { resolved:
        { '/home/jlafosse/test/sortablejs/react-sortable-mixin':
           { exports: null,
             depends: { sortablejs: 'Sortable' } } } } ] }

{ file: '/home/jlafosse/test/index.js',
  info:
   { package_json: '/home/jlafosse/test/package.json',
     packageDir: '/home/jlafosse/test',
     resolvedPreviously: true,
     shim: undefined,
     exposeGlobals: { react: 'React', sortablejs: 'Sortable' },
     browser: undefined,
     'browserify-shim':
      { react: 'global:React',
        sortablejs: 'global:Sortable',
        'sortablejs/react-sortable-mixin': { depends: 'sortablejs:Sortable' } },
     dependencies: { react: '^0.14.8', sortablejs: '^1.4.2' } },
  messages: [] }

I know the global shimming works because React is not included in the bundle... however as mentioned above, Sortable is being included. Also if I simply require('sortablejs') instead of the sortablejs/react-sortable-mixin in my index.js file, Sortable WILL NOT be included in the bundle as expected so my thought is that either my config is wrong or the module format for react-sortable-mixin does not respect browserify-shim.
Any help is appreciated.

A: This isn't possible without modifying the contents of the Sortable library. Browserify Shim alters your bundle.js file to either include window.PackageName or the entire package, depending on the browserify-shim directive in your package.json.
In your situation, when you require('sortablejs/react-sortable-mixin'); you're expecting Browserify Shim to alter the contents of node_modules/sortablejs/react-sortable-mixin.js such that require('./Sortable') becomes window.Sortable inside that file. The problem is that Browserify Shim doesn't alter the contents of the node_modules directory so this isn't possible.
There are a couple options:

*

*Rather than loading Sortable via CDN, load it globally via your bundle.js script to ensure it is only loaded once. Your index.js would change to:
window.Sortable = require('sortablejs');
var SortableMixin = require('sortablejs/react-sortable-mixin');

*Fork your own standalone file for react-sortable-mixin.js and bundle this directly in your bundle so that Browserify Shim can act on it.


text:
Q: Transmittance through a reversed one-way mirror I am looking to use a half silvered one-way mirror to allow as much light and solar energy as possible into a room where there are highly reflective surfaces within the room - and I want to keep the energy from reflecting back outside - trap as much light/energy as I can in the room. That's why I am wondering what percentage of sun-light would be transmitted through a "reversed" one-way mirror with the clear glass side of the mirror to the outside and the half-silvered side on the surface inside the room? And to what extent might this arrangement reflect solar light/energy back into the room?

A: There is no such thing as a one-way mirror.
If you want a mirror to reflect 99% of the light that tries to get out of the cavity, then that mirror will also need to reject 99% of the light that tries to get in.


text:
Q: After setting up an a Static IP address on netplan, I cant access the internet I am currently using ubuntu LTS and I am trying to set a static IP address because I plan on using K3sup.
After doing some research, I have changed
/etc/netplan/50-cloud-init.yaml

to these settings
# This file is generated from information provided by the datasource.  Changes
# to it will not persist across an instance reboot.  To disable cloud-init's
# network configuration capabilities, write a file
# /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg with the following:
# network: {config: disabled}
network:
    ethernets:
        eth0:
            dhcp4: false
            addresses: [192.168.1.83/24]
            gateway4: 192.168.0.1
            nameservers:
             addresses: [1.1.1.1, 8.8.8.8]
    version: 2

I have applied the settings and it has seemed to accept the new ip address. The problem is when I ping google, nothing goes through.
What is the issue here?


text:
Q: Want to get last value using regex having multiple slashes I have a string:
//abc.net/v1/hello/16546515646/abcdefgh

I want to get the value abcdefgh from above using regex.
I am using hello(\/.*)(\/.*), but it gives me the string hello/16546515646/abcdefgh
Can anybody provide the regex that how to get only  abcdefgh?

A: You can use this regex:
[^\/]+$

RegEx Demo
Breakup:
[^\/]+    # match anything that is not /
$         # followed by end of line

A: Here pattern that match letters from end:
'/\/\w+$/'


text:
Q: PHP - Fatal error: Cannot redeclare class Config in /path/to/Config.php on line 44 This is a WordPress local installation that I am trying to work with. I have not written a single line of this code myself. I don't understand what this error means:
Fatal error: Cannot redeclare class Config in /Applications/XAMPP/xamppfiles/lib/php/Config.php on line 44

Line 44 reads as follows:
class Config {

My guess is that a Config class has either already been declared elsewhere, or that this file is being executed for the second time.

A: That usually happens when you declare a class more than once in a page -- maybe via multiple includes.
To avoid this, use require_once instead. If you use require_once PHP will check if the file has already been included, and if so, not include (require) it again.
Say, for example, you have the following code:
<?php

class foo {
    # code
}

... more code ...

class foo { // trying to re-declare
    #code
}

In this case, PHP will throw a fatal error similar to the one below:

Fatal error: Cannot redeclare class foo in /path/to/script.php on line 7

In this case it's very simple -- simply find the 7th line of your code and remove the class declaration from there.
Alternativey, to make sure you don't try to re-declare classes, you can use the handy class_exists() function:
if(!class_exists('foo')) {
    class foo {
        # code
    }
}

The best approach, of course, would be to organize all the configurations in one single file called config.php and then require_once it everywhere. That way, you can be sure that it will be included only once.
As for debugging the error, you could use debug_print_backtrace().

A: It's possible that the theme you are using refers to a file called config.php. If so use the following steps.

*

*Try to find the config.php file and change it's name to configuration.php.

*Find the files where they use config.php in the code and change it to configuration.php.


text:
Q: change input value before submit form using jQuery I want to set hidden input value(username) based on client other input(email) in a form, then submit to server. (to make sure username equal to email)
However, the assignment to the hidden input is processed AFTER the form submitted. So 'username' is already None on server side.
<form id="altForm" action="" method="post">

<input type="hidden" name="username" id="id_username" maxlength="40" >

<input type="email" name="email" id="id_email" maxlength="40">

<input class="btn btn-primary pull-right" type="submit" value="Register" />
</form>

<script>

    $("#altForm").submit(function(e){
        e.preventDefault();
        var username = $("#id_email").val();
        $("#id_username").val(username);

    });

</script>

A: I would do this serverside, but if you want it clientside you can also accomplish it like this:
$('#id_email').keyup(function() {
    $('#id_username').val($(this).val());
});


text:
Q: loading a txt or xls to JTable I'm trying to load a txt file that holds all the information I want to load to the JTable but I don't know how to do so.
I looked for a solution but couldn't really find one. PLEASE HELP!
here is my code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.FileWriter;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;

public class Table2 extends JFrame implements ActionListener, TableModelListener{

//String[] column = {"Name","Age","Gender"};
Object[][] data = {{"John","20","Male"}};
JTable table = new JTable(new DefaultTableModel(data, new Object[]{"Name", "Age","Gender"})){

        public Component prepareRenderer(TableCellRenderer r, int data, int col){ //gives a pattern to the table cells.
        Component c = super.prepareRenderer(r, data, col);

        if(data % 2 == 0){
            c.setBackground(Color.PINK);
        }
        else{
            c.setBackground(Color.LIGHT_GRAY);
        }
        return c;
    }

};

//JTable table = new JTable(data,column);

public Table2(){

    table.setPreferredScrollableViewportSize(new Dimension(300,200));
    table.setFillsViewportHeight(true);

    JScrollPane scrollpane = new JScrollPane(table);
    add(scrollpane);

    table.getModel().addTableModelListener(this); //Adds the model listener to the table. (checks if any changes are made and activated on table changed method.)
}

public static void main(String[] args) {

    Table2 table = new Table2();
    table.setLayout(new FlowLayout());
    table.setVisible(true);
    table.setSize(400,300);
    table.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    table.setResizable(false);
    table.setTitle("Table Prictice on JFrame");
    //table.pack();

    JButton button = new JButton("Add");
    table.add(button);
    button.addActionListener(table);
}

public void actionPerformed(ActionEvent e) {

    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.addRow(new Object[]{"", "", ""});
    System.out.println("Action Performed!");
}

@Override
public void tableChanged(TableModelEvent e) {

    System.out.println("Table change detected by tableChange method!");
    int row = e.getFirstRow();
    int column = e.getColumn();
    TableModel model = (TableModel)e.getSource();
    String columnName = model.getColumnName(column);
    System.out.println("---TEST LINE---");

    try {

        saveTable();
    }

    catch (Exception e2) {

        e2.printStackTrace();
    }
}

public void saveTable()throws Exception
{
  BufferedWriter bfw = new BufferedWriter(new FileWriter("Table Data.txt")); //use Excel extension once finished. (txt for now)
  for(int i = 0 ; i < table.getColumnCount() ; i++)
  {
    bfw.write(table.getColumnName(i));
    bfw.write("\t");
  }

  for (int i = 0 ; i < table.getRowCount(); i++)
  {
    bfw.newLine();
    for(int j = 0 ; j < table.getColumnCount();j++)
    {
      bfw.write((String)(table.getValueAt(i,j)));
      bfw.write("\t");;
    }
  }
  bfw.close();
}

}

Basically I want to load the txt file each time I relaunch the program so that all of the information is stored.

A: The code to load the data will be the opposite of your code to write the data:

*

*Read a line of data from your file

*Use the String.split(...) to create an array of values for each colum

*Use the DefaultTableModel.addRow(...) method to add the Array to the TableModel

*Repeat steps 1-3 until all the data has been read and the add the TableModel to the JTable using the JTable.setModel(...) method.


text:
Q: php two self submitting forms on one page I have a webpage form that submits to itself to carry out php action.  I want to add a second form to this same webpage that is capable of self submit as well but I am not having any luck finding a working solution for my setup.  Here is what my webpage looks like.
First, it checks to see if the page has already been submitted, and if it has, it redirects elsewhere.
if($_SERVER['REQUEST_METHOD'] == "POST") {
header("Location: viewcustomers.php");
}

Next, the form itself.
<form id="addCustomer" method="POST" action=""> ..stuff.. </form>

Then, finally my form action.
if('POST' == $_SERVER['REQUEST_METHOD']) {
..phpstuff..
}

How could I adjust this form action (or add another) to differentiate between two different forms?
Thanks.

A: Easy!
<?php
    if(isset($_POST['action']) && $_POST['action'] == 'form1') {
        // Form 1
    } else if(isset($_POST['action']) && $_POST['action'] == 'form2') {
        // Form 2
    }
?>

<form action="#" method="post">

    <input type="hidden" name="action" value="form1" />
</form>

<form action="#" method="post">

    <input type="hidden" name="action" value="form2" />
</form>


text:
Q: Replace HTML attributes with CSS I have many html files generated by some coworkers through Dreamweaver CS5.5 and (worse!) Frontpage 2003.  The source for these files looks horrendous and I am tasked with updating them to HTML5 format.  I found tools online for stripping out inline css and adding the code to external sheets as well as combining and merging multiple css files into a single file.
What I want to find is some system of taking the outdated html attributes such as align, valign, bgcolor, width, height, etc. and replacing them with css code.  It's way too much to do manually so I thought I could get some ideas on software to help me do this.  Thanks.
Edit: Henry wants to know the tools I found.  Here they are:
http://inlinecssextractor.com/home.html (Inline CSS Extractor)
http://www.minifycss.com/css-compressor/ (CSS Compressor)

A: For the CSS part, fantasai will help you styling in modern CSS each deprecated attribute you removed (or replaced by a class having the same styling)
Good luck with the <ms:o part. And <font> :/


text:
Q: Hive always run mapred jobs in local mode We are testing a multi node hadoop cluster (2.4.0) with Hive (0.13.0). The cluster works fine, but when we runa a query in hive, the mapred job are always executed locally.
For example:
Without hive-site.xml (in fact, without any configuration file other than defaults) we set mapred.job.tracker:
hive> SET mapred.job.tracker=192.168.7.183:8032;

And run a query:
hive> select count(1) from suricata;

Total jobs = 1
Launching Job 1 out of 1
Number of reduce tasks determined at compile time: 1
In order to change the average load for a reducer (in bytes):
  set hive.exec.reducers.bytes.per.reducer=<number>
In order to limit the maximum number of reducers:
  set hive.exec.reducers.max=<number>
In order to set a constant number of reducers:
  set mapreduce.job.reduces=<number>
OpenJDK 64-Bit Server VM warning: You have loaded library /hadoop/hadoop-2.4.0/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
14/04/29 12:48:02 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
14/04/29 12:48:02 WARN conf.Configuration: file:/tmp/hadoopuser/hive_2014-04-29_12-47-57_290_2455239450939088471-1/-local-10003/jobconf.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
14/04/29 12:48:02 WARN conf.Configuration: file:/tmp/hadoopuser/hive_2014-04-29_12-47-57_290_2455239450939088471-1/-local-10003/jobconf.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
Execution log at: /tmp/hadoopuser/hadoopuser_20140429124747_badfcce6-620e-4718-8c3b-e4ef76bdba7e.log
Job running in-process (local Hadoop)
Hadoop job information for null: number of mappers: 0; number of reducers: 0
2014-04-29 12:48:05,450 null map = 0%,  reduce = 0%
.......
.......
2014-04-29 12:52:26,982 null map = 100%,  reduce = 100%
Ended Job = job_local1983771849_0001
Execution completed successfully
**MapredLocal task succeeded**
OK
266559841
Time taken: 270.176 seconds, Fetched: 1 row(s)

What are we missing?

A: Set hive.exec.mode.local.auto as false which will disable the local mode execution in Hive

A: For each query the compiler generates DAG of map-reduce jobs. If the job runs in  local mode, check below properties:
mapreduce.framework.name=local;
hive.exec.mode.local.auto=false;

If auto option is enabled then hive run the job in local mode if
Total input size < hive.exec.mode.local.auto.inputbytes.max
Total number of map tasks < hive.exec.mode.local.auto.tasks.max
Total number of reduce tasks =< 1 or 0

These options are available from 0.7


text:
Q: How to insert column_name as string in procedure while dynamically selecting value through select query which is containing same column_name dummy table
row_id   information_date
1        10-oct-1987
2        NULL

tbl_error

row_id       column_name
2            information_date

create or replace procedure test(column_name in varchar2)
as
begin
    insert into tbl_error
    values(select row_id , column_name from dummy where column_name IS
NULL);

end;
end test;

--calling
call test('information_date');

OUTPUT
tbl_error
row_id     column_name
2          NULL

I want to log 'information_date' into tbl_error but when executing it is storing NULL because it is taking value from dummy how to insert as string.
Desired output
ROW_ID  COLUMN_NAME
2       INFORMATION_DATE

A: solution is
insert into tbl_error
    values(select row_id , chr(39) || column_name || chr(39) from dummy where column_name IS NULL);


text:
Q: jQuery - Return items by selected SKU number I am trying to create a purchase receipt interaction where the user clicks a SKU number and all list items with the same SKU are cloned to a list to show all matching items with the same SKU.
Instead of appending the original list items, I want to return matching results to the modal so that if you click a different SKU, the results are replaced by the last selected SKU.

$("li a").click(function() {
  var item = $(this).closest("li");
  var sku = $(this).html();

  var $parent = $("li#" + sku);
  $parent = $('
')
    .clone()
    .appendTo(".modal");
});
ul {
  height: 200px;
  width: 200px;
  margin-block-start: 0;
  margin-block-end: 0;
}

li {
  display: flex;
  align-items: center;
  border: 1px solid;
  padding: 0.9rem 0rem;
}

li a:hover {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}

.bullet {
  margin: 0.3rem;
  border-radius: 50%;
  height: 25px;
  width: 25px;
}

.blue {
  background: blue;
}

.red {
  background: red;
}

.green {
  background: green;
}

.wrap {
  display: flex
}

.modal {
  height: 200px;
  width: 200px;
  border: 1px solid;
}

      1234

      0808

      9011

      1234

      9011

A: I prefer to use data attribute in this case instead of using .html() to get the value

*

*Add the data-sku for each  with its number

*Filter the li which contains the  with the same sku

*change the modal with .html()

*Be careful When taking a clone of lis and append it to the div.modal it will be
s in
 and that is an invalid structure so you need to change  ul').html(....) .. Then you'll need to separate the
 in the css one for the ul in .wrap and another for ul in the .modal

$(document).on('click',".wrap > ul > li:not(.appended) > a",function() {
  var sku = $(this).data('sku');    // get data sku
  var FilTer = $('a[data-sku="'+sku+'"]').closest('li').clone(); // filter li which contains same data sku and get clone from it
  $('.wrap > ul > li').removeClass('appended').filter(function(){ // remove the class `appended` from all the `wrap li`s then filter `li`
    return $(this).find('a[data-sku="'+sku+'"]').length; // return just the li which contains the a with data-sku
  }).addClass('appended'); // add class appended to this li
  $('.modal > ul').html(FilTer); // change the modal html with the filtered html
});
ul {
  height: 200px;
  width: 200px;
  margin-block-start: 0;
  margin-block-end: 0;
}

li {
  display: flex;
  align-items: center;
  border: 1px solid;
  padding: 0.9rem 0rem;
}

li a:hover {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}

.bullet {
  margin: 0.3rem;
  border-radius: 50%;
  height: 25px;
  width: 25px;
}

.blue {
  background: blue;
}

.red {
  background: red;
}

.green {
  background: green;
}

.wrap {
  display: flex
}

.modal {
  height: 200px;
  width: 200px;
  border: 1px solid;
}

      1234

      0808

      9011

      1234

      9011

Explanation To avoid cloning and appending on each click

*

*You need to set class (e.g: appended) to the appended li

*To get the click event work with the appended class you'll need $(document).on('click',".wrap > ul > li:not(.appended) > a",function() {

*It will be better to use > sign in selector to get only the li and a in wrap element


text:
Q: How to create a html form associated with this code I have piece of code (imageupload.php) below where the php is suppose to upload a file into the server and insert data into the database.
 <?php
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
    }

    $result = 0;

    //UPLOAD IMAGE FILE

    move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);

    $result = 1;

    //INSERT INTO IMAGE DATABASE TABLE

    $imagesql = "INSERT INTO Image (ImageFile) VALUES (?)";

    if (!$insert = $mysqli->prepare($imagesql)) {
        // Handle errors with prepare operation here
    }

    //Dont pass data directly to bind_param store it in a variable
    $insert->bind_param("s", $img);

    //Assign the variable
    $img = 'ImageFiles/' . $_FILES['fileImage']['name'];

    $insert->execute();

    $insertimagequestion->execute();

    //IF ANY ERROR WHILE INSERTING DATA INTO EITHER OF THE TABLES
    if ($insert->errno) {
      // Handle query error here
    }

    $insert->close();

    }
    ?>

But I want to create html form to associate with this but I have never created a file input in html. Does anybody know how to create the html form that can be associated with this?
I want a html code so that I can test the code above and then be able to test for any errors if there are any.

A: You can make HTML form as below:
<form action="http://www.example.com/upload.php"
enctype="multipart/form-data" method="post">

Please specify a file, or a set of files:

<input type="file" name="fileImage" size="40">

<input type="submit" value="Send">

</form>


text:
Q: Process with administrative privileges run on user logon I'm trying to figure out how to solve the privilege acquisition.
The application requires a desktop access, so it cannot be executed as a Windows service: it have to create a window for receiving message sent by other processes using SendMessage (it must be used for waiting message acknowledge).
The application shall be started when an user login, and it will manage the user session (manage applications, windows...). Only one user can be managed at time.
What I'm asking is which is the best solution for requesting privilege acquisition, since the application requires it (execute a process which calls SetWindowsHook).

*

*How it possible to run any process at user login with (higher) privileges, possibly without prompting UAC messages? The setup operations could be peformed during the installation phase...

*How could be possible to run an utility service starting a process when user logon? In this way the (installed) service could run the effective process with any priviledges...

*Any other solution? *

What are the definive action to be taken for having a full compatible UAC application? (I mean in the build and deploy phases?
For example, I am including the following manifest file using mt.exe (using VS2005):
<?xml version="1.0" encoding="utf-8"?>
<asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1"     xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-    com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
    security>
      <applicationRequestMinimum>
        <defaultAssemblyRequest permissionSetReference="Custom" />
        <PermissionSet class="System.Security.PermissionSet" version="1"     Unrestricted="true" ID="Custom" SameSite="site" />
      </applicationRequestMinimum>
        <requestedPrivileges>
                <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>
        </requestedPrivileges>
    </security>
  </trustInfo>
</asmv1:assembly>

It seems correct to you? No, because it doesn't work to me...
*
It actually make sense to create an additional user account (but this shall work also on windows domains) with administrator privileges to execute a controlled environment. It could be also acceptable to create a working session (a new desktop station) without logging any user, but actually I don't know if it is possible.

A: You are asking a lot of questions inside of one question. There are many unclear subjects (unclear for me) about architecture of your solutions. It is also absolutely unclear for me why you need SetWindowsHook. So I try to answer only on the technical parts of your questions.
Starting of a program without prompting UAC is not a large problem and can be soleved with respect of manifestes.
Starting of a process on users's desktop from a service, so that the process runs not under users credentials, is tricky but possible. How I understand your service run under SYSTEM account. Then it has SE_TCB_NAME privilage. The service run in the session 0 (see http://www.microsoft.com/whdc/system/sysinternals/session0changes.mspx). If a user login, the processes which he see run on in the session 1 or higher. Under Windows XP the first logged user run use session 0 and only the next login (if fast switching is on) use session 1 etc. So on any operation system acn be required to start a process on other session. To do this you should use SetTokenInformation function with TokenSessionId parameter. I described details in Launching a process in user's session from a service.
In all cases you should monitor users logins and logoffs and should get users session id to be able to start a process on the session. You can do this in different ways. One of the most simple way is to have a application which runs in autostart (registerd unter HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run for example). This application communicate with your service and you get through impersonation the users token and the session id. Another way is usage of ISensLogon2 notifications (see http://msdn.microsoft.com/en-us/library/aa376863.aspx) of the System Event Notification Service (SENS).
One more small problem. Depend on account used for the process which you start on users desktop in can requires to change Security Descriptor of the Desktop and Windows Station objects with respect of OpenWindowStation, OpenDesktop and SetUserObjectSecurity (see http://msdn.microsoft.com/en-us/library/ms681928.aspx, http://msdn.microsoft.com/en-us/library/ms687107.aspx and http://support.microsoft.com/kb/165194)

A: Services are exempt from UAC. Scheduled tasks (that run at user logon) are not. If you don't want the UAC prompt, and yet you want to run at logon, your best bet is to write both and have them communicate. Set up a service to do the privileged thing - write to Program Files or HKLM or whatever. Have it autostart. Now set up a scheduled task that runs at user logon. When it wants the privileged thing done, it asks the service to do it. How they communicate is up to you and depends on what your app does. If you have a database involved you could have a table where the task wrote requests. Or you could use the file system. Or you could use more direct integration.
The manifest file you've included in your question will make your exe elevate. This will cause a UAC prompt which you say you don't want.
Finally, can you revisit why you need to be elevated? Is there no way you could rewrite this task so it writes to AppData or HKCU or some other less protected area? Then you can just write the task and be done with it and not have to deal with interacting with a service.

A: Why not have a windows service running as a high privilege account that carries out the required high privilege actions and also have a user level app that does any UI/interactive actions and comunicates with the windows serives using WCF?


text:
Q: I want when the user click on product url to change mean => example.dev/shop/5615156/LG-Controller slug/productName I want www.example.com/shop/slug/productname
I have a error :
     Missing required parameters for [Route: shop.show] [URI:
     shop/{slug}/{productName}]. (0)

my route for each product
                {{ route('shop.show',[$product->slug,$product->name]) }}

and is my shopcontroller
       public function show($slug,$productName)
       {
       $productslug = Product::where('slug',$slug)->firstOrFail();
      $productname = Product::where('name',$productName)->firstOrFail();
       $mightAlsoLike = Product::where('slug', '!=' ,$slug)-
          >MightAlsoLike()->get();

         return view('front.product')
               ->with('product', $productname)
              ->with('product', $productslug)
               ->with( 'mightAlsoLike', $mightAlsoLike);
            }

and is my web.php :
    Route::get('/shop/{slug}/{productName}', 'ShopController@show')->name('shop.show');

A: You have to pass key in case of multiple route parameters.
Route::get('/shop/{slug}/{productName}', 'ShopController@show')->name('shop.show');

And use route like this:
{{ route('shop.show',['slug'=>$product->slug,'productName'=>$product->name]) }}


text:
Q: Host Data Object set to Null Reference Unity3D? I am writing a multi player game. And doing a check OnGUI() that if there is any hostData do something.
if (hostData)
{
   for (int i = 0; i < hostData.Length; i++)
   {
       GUI.Button (new Rect (btnX * 2f + btnW, btnY * 1.2f + (btnH * i), btnW * 3f, btnH * 0.5f), hostData [i].gameName);
   }
}

But  I have filled host Data on a button click, while on the other hand OnGUI is always looking for if(hostData) that is why it gives Null reference.
How i check this if statement other then this. Help me out.

A: if (hostData) only works if hostData is a game object, or component. This is because Unity implemented the implicit operator.
In other words, if (gameObject) works as a shortcut to if (gameObject != null).
This doesn't work when you are using something else then game objects or components, such as arrays or lists. In that case you have to use != null.


text:
Q: A field or property with the name 'ActualService ' was not found on the selected data source As I am adding some columns to gridview, I have got the above error. But ActualService is the same Column that I have in database. Please help me to resolve this Error.
My Code:
<Columns>
     <asp:TemplateField HeaderText="PMRMName" SortExpression="PMRMName">
         <ItemTemplate>
            <asp:HyperLink runat="server" ID="HyperLink1" NavigateUrl='<%# "db_PmuKpi_CF_AllPMs.aspx?PMRMID="+ Eval("PMRMID") + "&PMRMName =" + Eval("PMRMName")%>' Text='<%# Eval("PMRMName","{0}")%>' Target="_blank"></asp:HyperLink>
            <asp:Label ID="lblRM" runat="server"></asp:Label>
         </ItemTemplate>
      </asp:TemplateField>

      <asp:BoundField DataField="BudgetRevenue" HeaderText="BudgetRevenue" SortExpression="BudgetRevenue" />
      <asp:BoundField DataField="BudgetCOGS" HeaderText="BudgetCOGS" SortExpression="BudgetCOGS" />
      <asp:BoundField DataField="BudgetService" HeaderText="BudgetService" SortExpression="BudgetService" />
      <asp:BoundField DataField="BudgetCashFlow" HeaderText="BudgetCashFlow" SortExpression="BudgetCashFlow" />
      <asp:BoundField DataField="ActualRevenue" HeaderText="ActualRevenue" SortExpression="ActualRevenue" />
      <asp:BoundField DataField="ActualCOGS" HeaderText="ActualCOGS" SortExpression="ActualCOGS" />
      <asp:BoundField DataField="ActualService " HeaderText="ActualService " SortExpression="ActualService " />
      <asp:BoundField DataField="ActualCashFlow " HeaderText="ActualCashFlow " SortExpression="ActualCashFlow " />
</Columns>

I use the follwing SQL:
select PMRMID,PMRMName,BudgetRevenue,BudgetCOGS,BudgetService,BudgetCashFlow, ActualRevenue, ActualCOGS, ActualService,ActualCashFlow from [fn_pmukpi_CurrentMonthCF_AllRMs] ---------my function –

A: You have a space after "ActualService " and "ActualCashFlow " in your column name of the BoundField (DataField).


text:
Q: ngx ui tour pop-up guide background is transparent I use ngx ui tour and the pop-up background is transparent. Generally I think the style is no where. It looks like that
I've updated every angular version.


text:
Q: I need help for my basic drag and drop program I have put together a program for me and my friends to use while playing D&D and the basic premise is that the user can upload an image of the map they want to use and then they can upload an image of the character they want to use and drang drop the character around the map. I have only set it up to take one charecter for now just until I get it working properly.
The problem I am encountering is when I run it the drag isDragging flag is remaining false, so it seems that the dragStart is not starting so the drag is not working at all.
Code Posted Below -

  <form id="upload-form">
    <input type="file" id="upload-map-input" accept="image/*">
    <input type="file" id="upload-character-input" accept="image/*">
  </form>

Any help is appreciated.


text:
Q: Intent shows null value while for Array List? I am passing Array List of string values to next activity,
some mobile it is working properly ,in some it does not pass values.

A: The probably doesn't work on some devices because you are trying to pass too much data and you are overflowing the internal buffer that is used for IPC (interprocess communication). In general you shouldn't pass large arrays in an Intent. There are other ways of doing this:

*

*Share the data directly between multiple Activities by storing the data in a public static variable.

*Store the data in some persistent storage (file, SQLite database, SharedPreferences