text:
Q: How to use os.system (or alternative) to remotely shutdown any system? I am trying to use the call below to shut down my system, but I would like it to work on all major OS distro's. Is there a catch all shutdown command?
import os
os.system("shutdown /s /t 1")

Is there any other way to shutdown a machine remotely through python code?

A: For managing nodes remotely, ansible is a very nice tool, with gather facts you can get the current node os, then conditionally shut down accordingly.

A: Following function provides portable way of sending commands to remote host:
def run_shell_remote_command(remote_host, remote_cmd, pem_file=None, ignore_errors=False):
    remote_cmd = remote_cmd.split(' ')
    cmd = [SSH_PATH, '-o ConnectTimeout=30', '-o BatchMode=yes', '-o StrictHostKeyChecking=no']
    if pem_file:
        cmd.extend(['-i', pem_file])
    cmd.extend([remote_host] + remote_cmd)
    print(f"SSH CMD: {cmd}")
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        if not ignore_errors:
            raise RuntimeError("%r failed, status code %s stdout %r stderr %r" % (
                remote_cmd, p.returncode, stdout, stderr))
    return stdout.strip()  # This is the stdout from the shell command

That way you can run any command on remote host, which are supported by remote OS.


text:
Q: What is View Injection in Java/Android? Can anyone tell me what is actually 'View Injection' in Android? What is happening when we use View injection library like ButterKnife and inject views?
PS: I know how to use Butterknife I only want to know how to answer if someone ask me what is View Injection in Android.

A: ButterKnife is a library for using annotations in place of boilerplate code that we all do over and over again.
View injection is a concept in the MVC/MVVM design patterns that's all about decoupling the Views from their respective Controllers/View-Models.
Here is a very good explanation + example: http://www.developmentalmadness.com/2009/10/15/mvvm-with-prism-101-ndash-part-3b-view-injection-and/
With respect to ButterKnife, I don't know if it does much more than save you the need for fineViewById, but I haven't used ButterKnife yet so maybe I'm just not familiar with its capabilities.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calculate outcome from two selects into a new Select I have two Selects:
SELECT SUM(BetragSw) FROM bi_Budget WHERE Konto_KontoNrFIB = Buchungen_KontoNrFIB  and Konto_KontoNrFIB = '344100'

SELECT SUM(BetragSw) FROM bi_Budget WHERE Konto_KontoNrFIB = GegKontoNr  and GegKontoNr = '344100'

Now i have to make a new select around this two where i want to calculate value from first select - second select.
I can't make it work..
Lets say results Select 1 = 100 , Select 2 = 60. My goal is to have only one column with a Total of 40 (100-60)

A: It depends on the use you want to do afterwards, but strictly speaking about the example, this should work. Note that second select has been *(-1)
SELECT SUM(AMOUNT)
FROM
    (SELECT SUM(BetragSw) AS AMOUNT
     FROM bi_Budget
     WHERE Konto_KontoNrFIB = Buchungen_KontoNrFIB
       AND Konto_KontoNrFIB = '344100'
    UNION ALL
    SELECT -SUM(BetragSw) AS AMOUNT
    FROM bi_Budget
    WHERE Konto_KontoNrFIB = GegKontoNr
      AND GegKontoNr = '344100') AS X

A: You can use conditional aggregation to get your desired result with a single SELECT:
SELECT SUM(CASE WHEN Konto_KontoNrFIB = Buchungen_KontoNrFIB AND Konto_KontoNrFIB = '344100' THEN BetragSw ELSE 0 END) -
       SUM(CASE WHEN Konto_KontoNrFIB = GegKontoNr AND GegKontoNr = '344100' THEN BetragSw ELSE 0 END) AS total
FROM bi_Budget

A: You can write this as:
SELECT SUM(CASE WHEN Konto_KontoNrFIB = Buchungen_KontoNrFIB THEN BetragSw
                WHEN Konto_KontoNrFIB = GegKontoNr THEN - BetragSw
                ELSE 0
           END)
FROM bi_Budget
WHERE Konto_KontoNrFIB = '344100';


text:
Q: Typescript: widening a JSON type to accept interfaces This is an extension of Typescript: passing interface as parameter for a function that expects a JSON type (asking about passing interfaces to JSON typed functions), which in turn is an extension of Typescript: interface that extends a JSON type (asking about casting to/from JSON types)
These questions relate to a JSON Typescript type:
type JSONValue =
 | string
 | number
 | boolean
 | null
 | JSONValue[]
 | {[key: string]: JSONValue}

In Typescript: passing interface as parameter for a function that expects a JSON type, the final answer indicates that it is not possible to pass an interface to a function that expects a JSON value. In particular, the following code:
interface Foo {
  name: 'FOO',
  fooProp: string
}

const bar = (foo: Foo) => { return foo }

const wrap = <T extends JSONValue[]>(
  fn: (...args: T) => JSONValue,
  ...args: T
) => {
  return fn(...args);
}

wrap(bar, { name: 'FOO', fooProp: 'hello'});

fails because the interface Foo cannot be assigned to JSONValue even though analytically it is easy to recognize that the cast should be fine.
see playground, as well as https://github.com/microsoft/TypeScript/issues/15300
The previous answer stated:

The only workaround we have without widening the JSONValue type is to convert [interface] Foo to be a type.

In my case, I can modify the JSONValue type but cannot easily modify all of the relevant interfaces. What would widening the JSONValue type entail?

A: What I initially meant in my answer was to loosen the type JSONValue. You could settle for the object type.
const wrap = <T extends object[]>(
  fn: (...args: T) => object,
  ...args: T
) => {
  return fn(...args);
}

But you are essentially losing type safety as the function now accepts types which should be invalid like
interface Foo {
  name: 'FOO',
  fooProp: string,
  fn: () => void
}

which has a property fn with a function type. Ideally we would not allow this type to be passed to the function.

But not all hope is lost. We have one option left: infer the types into a generic type and recursively validate it.
type ValidateJSON<T> = {
  [K in keyof T]: T[K] extends JSONValue
    ? T[K]
    : T[K] extends Function  // we will blacklist the function type
      ? never
      : T[K] extends object
        ? ValidateJSON<T[K]>
        : never              // everything that is not an object type or part of JSONValue will resolve to never
} extends infer U ? { [K in keyof U]: U[K] } : never

ValidateJSON takes some type T and traverses through its type. It checks the property of the type and resolves them to never if the type should not be valid.
interface Foo {
  name: 'FOO',
  fooProp: string,
  fn: () => void
}

type Validated = ValidateJSON<Foo>
// {
//     name: 'FOO';
//     fooProp: string;
//     fn: never;
// }

We can use this utility type to validate both the parameter type and the return type of fn inside of wrap.
const wrap = <T extends any[], R extends ValidateJSON<R>>(
  fn: (...args: T) => R,
  ...args: { [K in keyof T]: ValidateJSON<T[K]> }
) => {
  return fn(...args as any);
}

Which all leads to the following behaviour:
// ok
wrap(
  (foo: Foo) => { return foo },
  { name: 'FOO', fooProp: 'hello' }
);

// not ok, foo has a parameter type which includes a function
wrap(
  (foo: Foo & { fn: () => void }) => { return foo },
  { name: 'FOO', fooProp: 'hello', fn: () => {} }
);

// not ok, fn returns an object which includes a function
wrap(
  (foo: Foo) => { return { ...foo, fn: () => {} } },
  { name: 'FOO', fooProp: 'hello' }
);

// not ok, foo has a parameter type which includes undefined
wrap(
  (foo: Foo & { c: undefined }) => { return foo },
  { name: 'FOO', fooProp: 'hello', c: undefined }
);

Playground

A: If you use a separate generic for the return type (which also extends JsonValue, then you won't have a type compatibility issue, and you can also infer a more narrow return type:
function wrap <A extends JsonValue[], T extends JsonValue>(
  fn: (...args: A) => T,
  ...args: A
): T {
  return fn(...args);
}

const result = wrap(bar, { name: 'FOO', fooProp: 'hello'});  // ok
    //^? const result: Foo

On the JsonValue type that you showed: for the union member which has string keys and JsonValue values (the object type): it is more correct to include undefined in a union with JsonValue, making the keys effectively optional... because there will never be a value at every key in an object, and the value that results from accessing a key that doesn't exist on an object is undefined at runtime:
type JsonValue =
  | string
  | number
  | boolean
  | null
  | JsonValue[]
  | { [key: string]: JsonValue | undefined };
//                             ^^^^^^^^^^^

This is compatible with the serialization and deserialization algorithms of the JSON object in JavaScript because it neither serializes properties with undefined as a value, nor does JSON support undefined as a type, so undefined will never exist in a deserialized value.
This type is both convenient (you can use dot notation property access for any property name) and type-safe (you must narrow each value to be JsonValue to safely use it as such).
Full code in TS Playground

Update in response to your comment:

the answer in the playground still depends on interface Foo being a type. But I need it to be an interface. Is this possible?

It is only possible if the interface extends (is constrained by) the object-like union member of JsonValue.
The TS handbook section Differences Between Type Aliases and Interfaces begins with this information (the emphasis is mine):

Type aliases and interfaces are very similar, and in many cases you can choose between them freely. Almost all features of an interface are available in type, the key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.

What this means is that each type alias is finalized at the site where it's defined... but an interface can always be extended (mutated), so the exact shape is not actually finalized until type-checking happens because other code (e.g. other code that consumes your code) can change it.
The only way to prevent this is to constrain which extensions are allowed for the interface in question:
An example using your original, unconstrained interface shows the compiler error:
interface Foo {
  name: 'FOO';
  fooProp: string;
}

const bar = (foo: Foo) => foo;

const result = wrap(bar, { name: 'FOO', fooProp: 'hello'});  /*
                    ~~~
Argument of type '(foo: Foo) => Foo' is not assignable to parameter of type '(...args: JsonValue[]) => JsonValue'.
  Types of parameters 'foo' and 'args' are incompatible.
    Type 'JsonValue' is not assignable to type 'Foo'.
      Type 'null' is not assignable to type 'Foo1'.(2345) */

However, if the interface is constrained to only allow compatibility with the object-like union member of JsonValue, then there are no potential type compatibility issues:
type JsonObject = { [key: string]: JsonValue | undefined };
//^ This type could be written with built-in type utilities a number of ways.
// I like this equivalent syntax:
// type JsonObject = Partial<Record<string, JsonValue>>;

interface Foo extends JsonObject {
  name: 'FOO';
  fooProp: string;
}

const bar = (foo: Foo) => foo;

const result = wrap(bar, { name: 'FOO', fooProp: 'hello'});  // ok

Code in TS Playground
See also: utility types
in the TS handbook


text:
Q: Rails in Apache I have my DocumentRoot for my virtualhost in Apache set up as the public dir of my rails app. The public dir contained the 'welcome aboard' rails index.html file, but i deleted it, created a controller called home, with the view 'index.' I then went into the config dir and uncommented root to: to point to home#index, but the website still just points to the public folder of the rails app, showing its contents. what did i do wrong?
home_controller.rb
class HomeController < ApplicationController
  def index
  end

end

routes.rb
Webapp::Application.routes.draw do
  get "home/index"
  #Lots of comments
  root :to => "home#index"

end

edit:
I got passenger working I think, but the routes.rb isn't working. It's not making the root my newest controller i made with rails generate controller home index. Instead it's looking for index.html in the public dir, because when i put an index.html file in there, it shows it, and if i remove it, i get an error 500. furthermore the apache error.log says "Premature end of script headers:"

A: Copy the whole tree to your dev computer.  Run it with the development server 'script/server'
Just use passenger in production.

A: "Error 500" probably can be detailed a little more. Check your log/production.log.
Alternatively, try to sun Passenger in standalone mode to see if any error comes up. Shutdown Apache and run:
sudo passenger start -p 80

Something else I usually do: edit your config/environments/production.rb to report detailed error messages:
config.consider_all_requests_local = true


text:
Q: AssetManager not loading file? I am on my way through the "Beginning Android Games" book by Mario Zechner I'm glad I picked it up but I am now running into an issue with one of the "Tests" he requires users to code early on in the book. Not that I am against coding them I would rather know what I am doing than to do a half cocked job and it not work out to well when I get further along.
So AssetManager does not seem to want to load my file.
    AssetManager am = getAssets();
    InputStream inputStream = null;
    try {
        am.open("assets/texts/hello.txt");
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {
        tv.setText("Could not Load file");
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                tv.setText("Could not close file");
            }
        }
    }
}

By all standards I should be able to just use the link: "texts/hello.txt" but every time I do it shoots an NPE at me. So I am forced to use the full link. Using the full link allows the program to run it just fails to load up my text document as per instructions it tells me "Could not load file"
Figured I would nip this issue in the bud now so it does not become a major issue later on.

A: Change you code as :
 AssetManager am = getAssets();
    InputStream inputStream = null;
    try {

         inputStream= am.open("texts/hello.txt"); //<<<<
        String text = loadTextFile(inputStream);
        tv.setText(text);
    } catch (IOException e) {

    // your code here

because you are passing null inputStream to loadTextFile method

A: // To load text file
        InputStream input;
        try {
          input = assetManager.open("helloworld.txt");

             int size = input.available();
             byte[] buffer = new byte[size];
             input.read(buffer);
             input.close();

             // byte buffer into a string
             String text = new String(buffer);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


text:
Q: Responsive table column by column I've build a responsive table like in this example . It works pretty well, but I do not want a break for all elements, I want to break the table by column. Means more like that on full view:
+----+----+----+----+
| A  | B  | C  | D  |    (TH)
+----+----+----+----+
| a  | b  | c  | d  |    (TR/TD)
+----+----+----+----+
| e  | f  | g  | h  |     (TR/TD)
+----+----+----+----+

And on 600 pixel with:
+----+----+----+
| A  | B  | C  |
+----+----+----+
| a  | b  | c  |
+----+----+----+
| D     d      |
+----+----+----+
| e  | f  | g  |
+----+----+----+
| D     h      |
+----+----+----+

On 400px I switch automatically to this card view:
+--------------+
| A     a      |
+--------------+
| B     b      |
+--------------+
| C     c      |
+--------------+
| D     d      |
+--------------+
+--------------+
| A     e      |
+--------------+
| B     f      |
+--------------+
| C     g      |
+--------------+
| D     h      |
+--------------+

Is there a way to do this with meta tags and CSS?


text:
Q: How can I intercept openGL function calls in Android framework? I know I can get openGL function calls by ADB(adb shell dumpsys gfxinfo) and Android Device Monitor. But I want to get them in a lower level(framework or driver...?). What should I supposed to do?

A: You can use a profiler tool from the vendor of the GPU used by the phone :

*

*Mali: Mali Graphics Debugger

*Adreno: Adreno GPU Profiler or the newer SnapDragon Profiler

*Nvidia: Nvidia PerfHUD
My preference goes to Adreno GPU profiler and PerfHUD, in my experience they are the most stable and they do not need to root the device.
Those tools are really usefull, you can:

*

*view all GL commands, shaders, textures etc.

*edit shaders while app is running

*get interesting performance metrics (ex: finding the heaviest draw calls)

*and many more things


text:
Q: What comes under onTabChanged in an onTabChangedListener? Consider the following scenario:
2 tabs in a parent activity. Each of them has a separate activity (please don't go about saying that this is deprecated and use fragments, I already know that). Now if I add a "OnTabChangeListener" and implement the abstract function "onTabChanged", in which cases will that function be called?
Only when the tabs are switched, i.e. I go from tab1 to tab2 (or the other way around) or also when from tab1/tab2 I go to another activity(not tab2/tab1, but something entirely different).
And is there a way to change the default behaviour?


text:
Q: How to minimize Shopware 572 html cache? I have a problem with the Shopware cache. We moved from 5.3.6 to 5.7.2 (with the middle step to 5.6.9). After a few minor problems shop was stable and running. Soon we realized that the cache folder becomes huge (30+gb) and clearing the cache from the backend is not possible because the request never finishes.
After a small research, we found that var/cache/production34234234/html folder is responsible for this.
The shop is in production mode, cache setup is basic, cache enabled, and automatic cache invalidation is enabled. That's all. It looks like Shopware creates too many HTML cache files.
Did anybody have a similar issue and how to solve it?


text:
Q: Calling an external API with keys and certificate from cloudpage We are trying to call an external API (Post request) with certificates and keys from SF cloud web page.
When we are calling the API from a linux machine (using CURL) it is working fine as we are able to provode the path for the certificate and key like in below syntax -
curl --key <key file path> --cert <cert file path> -X POST <api endpoint> -H 'Content-type: application/json' -H 'client_id:<client id>' -H 'client_secret: <secret key>' -H 'Authorization: Basic <auth token>' -d '{  "FIRST_NAME": "Ashley"}'
Response: OK

Does any one have an idea, how to configure the same post request in SF cloud page? (We have tried running AMP Script but we are not able to find a way to pass these certificates and keys).


text:
Q: Optimal way to fit images in an atlas? The AndEngine framework for Android has a way to load textures into an atlas. The atlas way of loading textures was new to me and so I looked into it. From what I've read around the forums, an atlas is a large rectangular region of image data where the width and height have to be powers of 2 (although they don't have to be equal, i.e. you can have a 512x1024 if you want). Textures are loaded into this region and this is used to keep them all in memory during the lifetime of the app. It allocates all of that space even if you don't use some of it.
With that in mind, what process can I use to optimally place an arbitrary number of graphics into the same atlas? I don't plan to do this at runtime within the app, but once all the graphics for my game have been created, I was hoping I could run the images and their sizes through some algorithm to determine how big to make the atlas and where each image should be loaded in it. Once I know those things, I can hard code their location for my game.
This is not an AndEngine or even Android specific question. I'm sure there are other graphics oriented frameworks that load textures this way.

A: I was about to post the question on Math.StackExchange.com but instead I found that it was already asked and already answered. There's even a link to a CodeProject article that does this for CSS Sprites.
EDIT: What I ended up doing in the long run was using a program called TexturePacker. Not only did it pack the images, it produced files to be used in AndEngine (as well as other supported platforms) and made the whole process easier for me.


text:
Q: How to optimize query with multiple % Please help me optimize my Mysql query below
SELECT * FROM `ticket` WHERE `ticket_id` LIKE '%wm%33%' LIMIT 0,1000

the table doesn't have full text index and i'm affraid that giving the column a full text index will cost time when table is needed to be always on

A: If you don't want to use a full text index, and I would suggest you do some benchmarking to see if the index adversely affects insert performance, you can restructure your data to eliminate the need for those sort of searches.
We don't know what's in ticket_id, but it's clear it has some sort of structure. Rather than parsing and searching this amalgamation, it's better to pull it apart into its individual pieces and recombine them.
To use a similar example, let's look at email addresses. What if you want to search for users whose email addresses are for gmail.com? The naive way to do this would be...
create table users (
  id serial primary key,
  email varchar(255) not null unique
);

select * from users
where email like '%@gmail.com'

There's the performance problem. There's also the problem of matching user@subdomain.gmail.com. like '%gmail.com' brings its own problems, it will match person@thingmail.com.
Instead, using generated columns we can split the domain from the email address and index it.
create table users (
  id serial primary key,
  email varchar(255) not null unique,
  domain varchar(255) as (
    substring_index(substring_index(email, '@', -1), '.', -2)
  ),

  index(domain)
);

Now matching the domain is a simple indexed equality check.
select * from users
where domain = 'gmail.com'

I expect you can do something similar for your ticket_id. Whether this is worth the effort requires some benchmarking, and also a consideration for complexity: a full text index is simpler and more flexible.
dbfiddle

A: WHERE `ticket_id` LIKE '%wm%33%'

may be replaced with
WHERE LOCATE('wm', ticket_id) < LOCATE('33', ticket_id) (see below)
I think it is less expensive.
PS. None indexing may help to improve such search performance...

Barmar: LOCATE() returns 0 if the string isn't found, so this will return rows that don't contain wm. Change it to
LOCATE('wm', ticket_id) BETWEEN 1 AND LOCATE('33', ticket_id)

That's true.


text:
Q: create site Collection from site template containing blog subsite sp2013 I want to create a site collection based on a site template that contains a calendar app and a blog subsite.
I explain, i have a site that contains a subsite of type blog site and also contains a calendar in sharepoint 2013, i saved the site as a template and checked include content.
However,
when i create a new sitecollection based on that template, i get the calendar app but never the blog subsite...
Am i missing something here? And how can we do this please?

A: site templates do not include subsites
you may want to create a separate template containing the blog as well
Trying to create a template with subsites


text:
Q: When is a forward declaration required? I have this C++ project that I'm working on.
All classes have their implementation separated from the .h file.
However, I'm not certain why/when forward declarations are required.
For example, I just ran into an error when I #included "ClassType.h", the compiler completely refused to compile a class that had a pointer to ClassType, even though class ClassType is clearly defined in "ClassType.h".
Why isn't it enough for the compiler to simply see that I've #included "ClassType.h", and WHY does it want a forward declaration?
#include "ClassType.h"

// REFUSES TO COMPILE WITHOUT forward declaration
class ClassType;

class SomeClass
{
    ClassType* instance;
};

A: Does ClassType.h include (directly or indirectly) the file you quoted, in which you're defining SomeClass?

A: I'm wondering if ClassType is declared in a namespace.  Need to see ClassType.h to be sure.

A: Sounds like you have the same header guard. Check that at the start of your header, you don't have something like this
#ifndef SOMECLASS_H

in both files. Those guards have to have unique names in every header file they guard from multiple inclusions. Otherwise, they will prevent inclusion of content into other headers.

A:
When is a forward declaration
  required?

It is needed when you only need to declare a pointer to a type, i.e. in a header file. The actual implementation is completely irrelevant and should only be needed in the .cpp files using any method or state of that class.
As long as a pointer is being copied, the type is irrelevant as you are merely just copying a pointer value, not the content of what the pointer points to.
// someclass.h
class ClassType;

class SomeClass
{
  public:
    void foo();
    ClassType* instance;
};

// someclass.cpp
void SomeClass::foo()
{
    instance->SomeMethod();  // someclass.h needed
    SomeFunction(instance);  // someclass.h irrelevant
}

Cheers
If this doesn't work, you probably have some problems with someclass.h

A: The problem probably exists with ClassType, and not SomeClass.  Please post the listing for ClassType.h, and I believe the community will be able to help you. :)

A: If you are using a forward declaration in order to get the compile to work, then ClassType.h has something that is making your ClassType definition not make into the pre-processed source that gets compiled. Try compiling so that it leave the pre-processed file around and see what you can find there.

A: In general, you need a forward declaration in any compile unit if the compiler hasn't seen the declaration he's trying to use. This means you need forward declarations

*

*if you have cyclic dependencies

*if the header doesn't properly declare the class (function, variable) you're trying to use.

Including a header file does not do any declarations -- it's just including a file, and that file could be very well empty (or made empty due to broken double inclusion protection, which can happen easily if you copy the header file from another one and forget to adjust the macro used for double inclusion protection).
In your case, I'd bet something is wrong with the ClassType.h file. If it does declares the class my guess is the double inclusion protection.

A: in case it is a header guard of a kind
#ifdef SOMECLASS_H

then it is better to use #pragma once instead


text:
Q: Problems Importing My Files I've recently gotten a new laptop and I am having problems importing my projects. I used Airdrop to import my projects into my new Eclipse folder. When I imported it shows errors. Any way to fix this?

A: Solved. Just make a new project and drag imported files from old computer to the new project.


text:
Q: Google chart control values to asp variable I have a Google-Graph with a range-slider control that I want to use to generate a file. I have ASP code for file generation so that's most of the work already done.
What I want to be able to do is read the 'start' and 'end' values from the range-slider and use those values to generate a file with only data in the range. So ultimately what I need is a way to read and store the range as an ASP variable.
Please note that this is 'ASP' not 'ASP.Net' (this was not my decision and can not be changed at this point)

A: There are many different ways to pass a set of values back to the server (AJAX and forms are two of the more common ones).  You can get the start and end of the range by calling the filter's getState method:
var state = filter.getState();

If you are using a ChartRangeFilter, the state has a range property with start and end properties:
var start = state.range.start;
var end = state.range.end;

If you are using a NumberRangeFilter or DateRangeFilter, state will have lowValue and highValue properties (plus a lowThumbAtMinimum and highThumbAtMinimum, which are probably not relevant to your needs):
var start = state.lowValue;
var end = state.highValue;

The data type of the values will be the same as the column they are filtering on (if you are filtering a "number" column, they are numbers; if you are filtering a "date" or "datetime" column, they are Date objects).
Use whatever method you choose to pass those values back to the server.


text:
Q: Storage place for CSS of custom 2sxc modules we use DNN, 2sxc and write 2sxc-modules for our needs with the help of the 2sxc Content object.
In one DNN-installation we have several portals (websites), all portals share the same 2sxc and the same custom skin "XYZ".
Our 2sxc cshtml-templates are stored in the folder Portals/_default/2sxc/Content/, for example   Portals/_default/2sxc/Content/history-module.cshtml.
Our skin folder is Portals/_default/Skins/XYZ/. Our main CSS file is Portals/_default/Skins/XYZ/xyz-skin.css.
We are not sure what is the best place to store CSS of our 2sxc cshtml-templates, so the question is about it. For example:

*

*Should the CSS of our custom History Module be stored directly in the history-module.cshtml in a <style>....</style>, so everything lays inside the 2sxc/Content/ folder?

*Or should the CSS of our History Module rather be stored in our main CSS file xyz-skin.css inside the Skins-folder? Where the file "xyz-skin.css" is included in Portals\_default\Skins\XYZ\footer_dnnincludes.inc.aspx the following way:

<dnn:DnnCssInclude ID="BootstrapCSS" runat="server" FilePath="assets/bootstrap-v4_3_1/bootstrap.min.css"  PathNameAlias="SkinPath" />
<dnn:DnnJsInclude ID="BootstrapJS" runat="server" FilePath="assets/bootstrap-v4_3_1/bootstrap.bundle.min.js" PathNameAlias="SkinPath" />
<dnn:DnnJsInclude runat="server" FilePath="assets/js/xyz-main-js-file.js" PathNameAlias="SkinPath" />
<dnn:DnnCssInclude ID="MainSkin" runat="server" FilePath="xyz-skin.css" PathNameAlias="SkinPath" />

*Or some other or mixed solution?

What is the correct way and what is best for the site performance?

A: The correct way is to put the CSS in an own file inside the app folder of that specific app.
It should then only be loaded if needed. So the App should then make sure the CSS is loaded.
Please check out the many sample apps on 2sxc.org/apps like the blog, news, etc. There you can see how it's done.


text:
Q: How to limit the input length on a v-select element? I use the Vue-select feature on my project, and in a v-select element I want to set up a maximum input length (45 characters), but I'm failing to do so. I managed to treat this on the back-end, but I'd like to prevent the user from inputing more than it's allowed.
I tried to use the property :maxlength="45" but it seems that it have absolutely no effect on the input length.
Here's what I have:

            <v-select taggable pushTags :maxlength="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

            Descarte

selecionarLote() {
    let vm = this;
    if (this.lotes.length) {
        if (!this.lote || !this.lote.label) return;

        if (this.lote.label.length > 45) {
            this.lote.label = this.lote.label.substring(0, 45);
        }

As I said, I can handle the inputs that are above 45 characters, but I'd like to prevent it, just like this code do: https://codepen.io/CSWApps/pen/RQbvvp, I searched the vue-select documentation and wasn't able to find a way to limit the input length.
Thanks for any help in advance.
--------------- EDIT ----------------------
I tried to use Michael's answer, but I could still type more than 45 characters:
  data() {
    return {
      maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"],
      lote: null,
      descarte: false,
      modelValidations: {
        requiredText: {
          required: true
        }
      }
    };
  }

            <v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
              Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

            Descarte

A: You need to provide it with one of the props of v-select, In this you can use rules like this:
<v-select taggable pushTags :rules="maxlength" v-model="lote" :options="lotes" @input="selecionarLote" >
                Digite o nome de um lote e clique "Enter" para adicionar...
            </v-select>

data(){
  return {
    maxlength: [v => v.length < 45 || "Sorry you have exceeded the max length of input"]
   }


text:
Q: sed inside tcsh foreach loop > foreach i ( `cat /home/chandran/scratch_r/review/1810a042/list2test` )
foreach? sed -i "/^$i /s/$/ ASAN ASAN_CUI/" testify.list
foreach? end
Illegal variable name.

A: > echo "$/"
Illegal variable name.
> echo '$/'
$/
> set i=blah
> echo "$i"'$/'
blah$/
> echo $i:q'$/'
blah$/

So:
sed -i '/^'$i:q' /s/$/ ASAN ASAN_CUI/' testify.list

Or use a shell with a cleaner/better/easier syntax like zsh:
zsh% for i ($(< ~/scratch_r/review/1810a042/list2test))
for>   sed -i "/^$i /s/$/ ASAN ASAN_CUI/" testify.list

Though here instead of rewriting the testify.list over and over, you could do it in one go:
sed -i "$(
    sed 's|.*|/^& /s/$/ ASAN ASAN_CUI/|' ~/scratch_r/review/1810a042/list2test
  )" testify.list

Or maybe:
perl -lapi -e 'BEGIN{while (<STDIN>) {chomp; $w{$_}++}}
               $_ .= " ASAN ASAN_CUI" if $w{$F[0]}
              ' testify.list < ~/scratch_r/review/1810a042/list2test

(none tested).
All those assuming the list2test contains one word per line, no blank, no /, no wildcards or regex operators...


text:
Q: How do I avoid using arrays? My professor wants us to write a program without using arrays or vectors like this:

Write a program using functions that calculates and prints parking charges for each of the n customers who parked their cars in the garage.
Parking rates:

*

*a parking garage charges a $5.00 minimum fee to park for up to five hours.

*the garage charges an additional $0.50 per hour for each hour or part thereof in the excess of five hours

*the maximum charge for any given 24hr period is $10.00. Assume that no car parks longer that 24 hours at a time.

  You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of your receipts.
The program output should look like this:
car------Hours------Charge

1--------2.00--------$5.00

2--------5.00--------$5.00

3--------5.30--------$5.50

etc.

total: 3---12.30----$15.50

I only managed to get this far:
include <iostream>
include <conio.h>
include <cmath>
include <iomanip>
using namespace std;
double calculate(double);
int main()
{
    double hours,charge;
    int finish;
    double sumhours;
    sumhours=0;
    finish=0;
    charge=0;
    int cars;
    cars=0;

    do
    {
        cout<<"Enter the number of hours the vehicle has been parked: "<<endl;
        cin>>hours;
        cars++;
        sumhours+=hours;
        finish=cin.get();
        if(hours>24)
        {
            cout<<"enter a time below 24hrs."<<endl;
            cars--;
            sumhours=sumhours-hours;
        }
    }
        while(finish!=EOF);

        double total=calculate(hours);
        cout<<total<<": "<<(cars-1)<<": "<<sumhours;

    while(!_kbhit());
    return 0;
}

double calculate(double time)
{
    double calculate=0;
    double fees;

    if(time<=5)
        return 5;
     if(time>15)
        return 10;

     time=ceil(time);
     fees=5+(.5*(time-5));

    return calculate;

}

A: Since this is homework, here is an algorithm:
1. Print header.
2.  Clear running total variables.
3.  While not end of file
3.1    read a record.
3.2    print record contents
3.3    add record field values to running total variables  (Hint! Hint!)
3.4.   end-while
4.  print out running total variables.
You may have to do some additional calculations with the running total variables, especially for averages.
Edit 1: Example of a running total variable
int sum = 0; // This is the running total variable.
const unsigned int QUANTITY = 23;
for (unsigned int i = 0; i < QUANTITY; ++i)
{
    cout << "Adding " << i << " to sum.\n";
    sum += i;
}
cout << "Sum is: " << sum << "\n";
cout.flush();

In this example, the data 'i' is not stored only used.  The sum variable is a running total.
Look for similarities in your assignment.
Edit 2:  Example of detecting end of input on cin
char reply = 'n';
while (tolower(reply) != 'y')
{
   cout << "Do you want to quit? (y/n)";
   cout.flush();
   cin >> reply;
   cin.ignore(1000, '\n'); // Eat up newline.
}
cout << "Thanks for the answer.\n";
cout.flush();

A: Since you can't use arrays or vectors, I think you should print the parking data for each car as it's being processed. Pseudocode:
While more cars:
    Read data for next car
    Calculate cost
    Print data
    Add to running totals
End while
Print totals

A: On every iteration, generate the relevant output, but don't stream it to std::cout.  Instead, stream it to a std::stringstream object.  Then, at the end, stream that object to std::cout.  The maths can be done simply by maintaining a running accumulation of the input values.
This, of course, assumes that using a std::stringstream is not considered "cheating" in the context of this homework exercise.

A: You can try storing your values in a linked list structure instead of an array. Linked lists work great for dynamic storage.
Try this tutorial, http://www.cprogramming.com/tutorial/lesson15.html

A: My suggestion then is to use a recursive method, the method first accepts input, asks if there is any more input. If there is more input, it then calls itself. If there is no more input, it outputs it's current car and then returns a sum that's added so far in a structure.
The only problem with this method is that it would output entered cars in reverse of input, but it would do so without an array or a file to save to.


text:
Q: Celery is rerunning long running completed tasks over and over I've a python celery-redis queue processing uploads and downloads worth gigs and gigs of data at a time.
Few of the uploads takes upto few hours. However once such a task finishes, I'm witnessing this bizarre celery behaviour that the celery scheduler is rerunning the just concluded task again by sending it again to the worker (I'm running a single worker) And it just happened 2times on the same task!
Can someone help me know why is this happening and how can I prevent it?
The tasks are definitely finishing cleanly with no errors reported just that these are extremely long running tasks.

A: I recently ran into this issue, and eventually figured out that tasks were
running multiple times because of a combination of
task prefetching and tasks exceeded the
visibility timeout. Tasks are acknowledged right before they're executed (unless you set ACKS_LATE=True),
and by default 4 tasks are prefetched per process. The first task will be
acknowledged before execution, but if it takes over an hour to execute then the
other prefetched tasks will be delivered to another worker where it will
be executed an additional time (or in your case,
executed an additional time by the same worker).
You can solve by increasing the visibility timeout to something longer than the longest possible runtime of your tasks:
BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600*10}  # 10 hours

You could also set PREFETCH_MULTIPLIER=1 to disable prefetching so that long running tasks don't keep
other tasks from being acknowledged.


text:
Q: who know how to compare two binary image and how to encode a binary image when we have two binary image,may be they are similar, How can we let computer knows it.
shall we do something such as encoding the binary image to compare, my question is how can I do that.

A: Looks like a great place to start here at a C-Sharp Corner post.


text:
Q: How to sticky nicedit panel? I think you know it, you have a larger text and the panel is at the top of your edit area and if you will use the panel you must scroll.
It would be nice, if the panel sticky at the top of the window, instead of going away.
Any idea, how to sticky the panel?

A: Easier than I thought.
var sticky_panelContain_offset_top = $('div.nicEdit-panelContain').offset().top;
    var sticky_panelContainer = function(){
    var scroll_top = $(window).scrollTop();
    if (scroll_top > sticky_panelContain_offset_top) {
        $('div.nicEdit-panelContain').css({ 'position': 'fixed', 'top':0, 'left':0 });
        } else {
        $('div.nicEdit-panelContain').css({ 'position': 'relative' });
    }
};
sticky_panelContainer();
$(window).scroll(function() {
    sticky_panelContainer();
});

But you must edit nicedit.js, because the buttontips and pulldowns will not work right. The topoffset start must be the panel top.
Open nicedit.js and search the "pos : function()", it is near the beginning.
And change
var curleft = curtop = 0;

in
var curleft = curtop = 0;
if ($('div.nicEdit-panelContain').css('position') == 'fixed') {
    curtop = $('div.nicEdit-panelContain').offset().top;
}

jsfiddle example


text:
Q: Use equalizer and an usb audio card I have Raspbian installed on my Rasperry Pi. I have a Delock USB Audio Card and setted it up, works good. My speaker set has a quite strong bass, so I need an equalizer.
There is an alsa plugin which gives me an equalizer, but it doesn't change the usb card sound. If I set the equalizer output as first output, I can't hear anything. I also tried "pulseaudio", but I don't get ho to set it up.
I'm not very familiar with such programs and quite new to Linux. I used this tutorial to set up the usb audio card: http://computers.tutsplus.com/articles/using-a-usb-audio-device-with-a-raspberry-pi--mac-55876
Can someone help me to install an equalizer?
edit:
At first I installed the alsa equal plugin. I added the asound.conf file:
ctl.equal {
type equal;
controls "/home/pi/.alsaequal.bin"
}

pcm.plugequal {
type equal;
slave.pcm "plughw:1,0";
controls "/home/pi/.alsaequal.bin"
}

pcm.equal {
type plug;
slave.pcm plugequal;
}

When I type ´alsamixer -D equal´ an equalizer shows up, but changing the values has no effects. I tried to change the line
pcm.equal {

to
pcm.!default {

and rebooted, but then I couldn't hear anything. That's where I am right now.


text:
Q: Best practice for normalizing output in regression I am working on some complicated regression problems that I am fitting with deep neural networks. In other to make these deep networks trainable, there are normalisation steps all over the place in my networks. The output in natural units is of course not normalised.
What I have been doing so far is adding a zero-bias simple multiplicative neuron at the end of each regression output, so that the network can learn an appropriate 'denormalisation' itself. However, I just realised this has a quite adverse effect on the speed of convergence of my network; likely due to the strong coupling of this neuron with all other unknowns, thus creating a very poorly conditioned 'valley' for gradient decent to contend with.
Initialising the weight of this denormalising neuron with for example the mean of the output vector helps a lot in further training; cutting the required iterations to get to the same loss by an order of magnitude. Yet I am worried I am still adversely influencing training despite the initialisation; even with good initialisation the condition number will likely suffer. Thats what happens when you add depth to a network in general, but do I have to waste my depth on this?
The obvious alternative is to do this kind of normalisation outside of my network. But then the ratio is non-trainable and might still 'clash' with the normalisation steps in the network. And I don't like having another little bit of state to keep track of in my model; its a single weight linear transform; my fancy computational graph framework should be able to handle it, right?
I feel like I am reinventing the wheel here. Searching the internet for best practices for this problem does not yield much. Anything you can recommend?
EDIT:
Having experimented with the options more, separately training the denormalisation layer from the rest of the network appears to be the most effective approach. That is, do separate training passes where only either the denormalisation layer or the rest of the network is trainable. However, it really uglifies my code, so I am not too happy with it. Overall the dynamic of such a denormalisation layer is really the same as a BatchNorm layer; it has its own micro-loss (match normal-data to non-normal data or vice-versa) that it optimizes for independently of the rest of the networks objectives by adjusting its internal state. However a denormalisation layer can only update during backprop since it needs to recieve the downstream signal to know how to update; so the implementation is hardly a copy-paste of a batchnorm layer; but I am hoping to create a clean and reusable component along these lines. But if anyone has suggestions along these lines they are very welcome too!

A: You can't best practice your way out of a problem you didn't best practice your way into. Get rid of the multiplicative output node. Use a normal 1-node output layer with linear activation and do include a bias. This is the default recommendation for regression, for good reason.
Roughly speaking, for intuition purposes only, this is the same as doing a normal linear regression as the final step in your process. Linear regression always gives the best linear unbiased estimate. In particular, the mean of your predictions is pretty much guaranteed to match the mean of your training set.
All of the learning happens in the hidden layers. By the time we get to the output layer, we don't need to do any more work - there are already plenty of features on the second-to-last layer that have very high mutual information with the output. All we need to do in the output layer is a little book-keeping - averaging together features and centering and scaling them so match the response variable $y$. And the usual 1-node linear response using bias output layer is perfect for that.


text:
Q: Python: Nested For Loops I have a question I need to ask you. Here is part of my script:
scan=file('indice.txt','r')
for i_L in range(10):
    for line in scan:
        a,b,c=line.split()
        do something ...
        ... ...
    print something
scan.close()

indice.txt is a file containing 3 columns of real numbers.
The main problem is that when the outer loop over i_L executes for the first value of i_L, the loop is broken and only one value is shown in the output.
anyone can help?

A: Before you start looping over the lines in the file again, you should seek the file to the beginning:
scan=file('indice.txt','r')
for i_L in range(10):
    for line in scan:
        a,b,c=line.split()
        do something ...

        ...
    print something
    scan.seek(0)
scan.close()

See file.seek.
You should also consider caching the lines first and then working with the cache.

A: You can also read all line at once into list, and keep using it (assuming this indice.txt is not like 500GB data)
scan=file('indice.txt','r')
lst_scan = list(scan)
scan.close()
for i_L in range(10):
    for line in lst_scan:
        a,b,c=line.split()
        do something ...

        ...
    print something

A: for line in file:
    ...

is a shorthand for
for line in iter(file.readline, ""):
    ...

So you can see actually it call readline which move the file's current position just as other
file operations. It won't go back to the beginning of the file when you iterate again, unless you set the current position manually, like:
yourfile.seek(0)

Also if you don't want to seek from the last position but not from the beginning, 2 "for..in.." is not a good way either, because it may have buffer of it, the right way to this is:
  it = iter(file)
  for line in it:
      if line == "\n":
          break
  for line in it:
      print line,

Please refer to PEP234 for more about this:
http://www.python.org/dev/peps/pep-0234/
It explains how different kinds of iterators work. And what happens when you iterate a file.


text:
Q: How can you add and multiple to True or False? I started learning python from a site, and it gave me a question that was kind of weird, I had to add and multiply a number to True and False. I've never done that before, so could someone explain what that means? (Can you replace True with 1 and False with 0?)
This is the question:
What is the value of result at the end of the following code?
x = 20
y = 5
result = (x + True) / (4 - y * False)

A)
False
B)
-21
C)
5
D)
5.25

A: The answer is 5.25 because in Python, True is equal to 1 while False is equal to 0.


text:
Q: JQuery hide and show doesnt work I have been trying to make a updateable grid.Which means i show an icon on mouseover
on click of that icon i show a new row with textboxes and hide the previous row then there is a an icon which saves the values using ajax.On Successfull completion of this ajax save process i make a new row of the data and replace the previous row with textboxes.
Problem is that i cant run mouseovers and other function using jQuery selectors as the newly replaced html will not be binded to it.I did a workaround for that i was calling:
jQuery('[rel="datepicker"]').datepicker();
          jQuery('[rel="innerRows"]').mouseover(function (){
          //alert('hererere');
            var spanId = jQuery(this).attr('spanid');
            jQuery('[rel="innerSpans"]').hide();
            jQuery('#edit_'+spanId).show();
          });
          jQuery('[rel="editButton"]').click(function (){
            var recordId = jQuery(this).attr('id');
            jQuery('#show_'+recordId).hide();
            jQuery('#hid_'+recordId).show();
          });
          jQuery('[rel="saveRecord"]').click(function (){
            var recordId = jQuery(this).attr('recId');
            var event    = jQuery.trim(jQuery('#event_'+recordId).val());
            var date     = jQuery.trim(jQuery('#date_'+recordId).val());
            var location = jQuery.trim(jQuery('#location_'+recordId).val());
            var notes    = jQuery.trim(jQuery('#notes_'+recordId).val());
            if(event !='' && date !='' && location !='' && notes !=''){
              jQuery.ajax({
                  url:'/application/saveevent/',
                  dataType: 'html',
                  data: '&recId='+recordId+'&event='+event+'&date='+date+'&location='+location+'&notes='+notes,
                  success : function (text){
                    jQuery('#hid_'+recordId).replaceWith(text);
                    bind();
                  }
              });
            }

to show and save the row.Now in the bind function i am again calling the above script to rebind the new html with jQuery selectors.
Problem is that in this bind function
 jQuery('[rel="innerSpans"]').hide();
            jQuery('#edit_'+spanId).show();

Doesnt work it does not show or hide the button inside the generated html
It is to show and hide the edit icons in the generated html which it doesnt.
Is it because of the element is in replaced html or what.
Please suggest.
This is the HTML.

                                Event
                                Date
                                Location
                                Notes

                                event of councils
                                02/08/2012
                                Canada
                                Call them

                                <input type="text" value="event of councils" id="event_6" name="data[event]">
                                <input type="text" value="02/08/2012" rel="datepicker" id="date_6" name="data[date]" class="hasDatepicker">
                                <input type="text" value="Canada" id="location_6" name="data[location]">
                                <input type="text" value="Call them" id="notes_6" name="data[notes]">

                                eventssssss
                                03/07/2012
                                Restaurant
                                Notes are here

                                <input type="text" value="eventssssss" id="event_7" name="data[event]">
                                <input type="text" value="03/07/2012" rel="datepicker" id="date_7" name="data[date]" class="hasDatepicker">
                                <input type="text" value="Restaurant" id="location_7" name="data[location]">
                                <input type="text" value="Notes are here" id="notes_7" name="data[notes]">

I replace the row with a new row which is updated.http://203.100.79.84:9733/
Regards
Himanshu Sharma

A: Have you tried using on() instead of mouseover()?
E.g:
jQuery('[rel="innerRows"]').on("mouseover", function (){

    var spanId = jQuery(this).attr('spanid');
    jQuery('[rel="innerSpans"]').hide();
    jQuery('#edit_'+spanId).show();
 });


text: Q: Getting all subway stations on Android app I'm looking for a way to get all subway stations from a country on Android app but I found nothing on how to do it. Seems there is already a feature request about it (https://issuetracker.google.com/issues/35827961) but it's 4 years old. Is there any another way to get that list please?


text:
Q: trato de hacer codigo aleatorio de 10 caracters alfanumericos en C, pero no me imprime bien el array que muestra el codigo el array "lista" es la ,lista de donde quiero coger caracters aleatorios y el array "identificador" es donde quiero colocar estos caracteres aleatorios.
#include "stdio.h"
    #include "stdlib.h"
    #include "time.h"

int main(void){

        char lista[]={0,1,2,3,4,5,6,7,8,9,"a","b","c","d","e","f","g","h","i","j","k","l","m","n","ñ","o","p","q","r","s","t","u","v","w","x","y","z"};
        char identificador[10];
        int j=rand() % 37;
        int i;
        srand(time(NULL));

        for(i=0;i<10;i++){

            identificador[j]=lista[j];
        }
        for (i=0;i<10;i++){
            printf("%d", lista[i]);
        }

    }

A: Estos son los errores que vi en tu código:

*

*Los números de lista[] deberían ser también strings para que se
puedan concatenar:

char lista[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

*

*Tal como te mencionan en los comentarios, no estás copiando los 10 caracteres aleatorios en el primer bucle. Lo que deberías hacer es que la operación rand() & 37 esté en cada bucle y almacenarlo en identificador[i] para que en el segundo for llames a identificador[i], mostrando éste los 10 caracteres alfanuméricos. Tu bucle for tendría que estar de la siguiente forma:

for (i = 0; i < 10; i++)
{
  int j = rand() % 37;
  identificador[i] = lista[j];
}

for (i = 0; i < 10; i++)
{
  printf("%c", identificador[i]);
}

Tu código final sería el siguiente:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    char lista[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    char identificador[10];
    int i;

    srand(time(NULL));

    for (i = 0; i < 10; i++)
    {
        int j = rand() % 37;
        identificador[i] = lista[j];
    }

    for (i = 0; i < 10; i++)
    {
        printf("%c", identificador[i]);
    }

    return 0;
}

Output:
// 1ifeo0nfnu
// 3nlll1lq6m

A: No es lo mismo un número que un carácter.
Los primeros son valores que se guardan tal cual en la memoria del equipo, mientras que para los segundos, lo que se almacenan son unos valores que no son sino unos índices que permiten localizar caracteres concretos en una tabla de caracteres.
Así, no es lo mismo el número 5 que el caracter '5'. El primero se representa con el valor 0x05 mientras que el segundo con el valor 0x35.
Lo que tienes que hacer, es convertir los números en caracteres:
char lista[]={'0','1','2','3','4','5','6','7','8','9'

Luego date cuenta que no es lo mismo un caracter que una cadena de caracteres... si te das cuenta, las letras las estás almacenando cono cadenas de caracteres, no como caracteres.
Ten en cuenta que una cadena de caracteres es realmente un puntero que apunta a la posición de memoria donde se almacena la secuencia de caracteres... los cuales terminan con el caracter nulo...
Lo dicho, reemplaza las comillas dobles por comillas simples.
Para terminar, al printf le tienes que decir que quieres imprimir caracteres, no números:
for (i=0;i<10;i++){
    printf("%c", lista[i]);


text:
Q: Querying inherited page types when using generated page type class I am attempting to use TreeProvider to query pages which all inherit from a base page type, here referred to as My.Product. I have also integrated the generated C# class for that base page type in order to get strongly-typed access to page type values.
The following query, without using the generated page type, works fine:
        //returns all products as TreeNode
        var products = tree.SelectNodes()
            .OnSite("MyWebSite")
            .Types("My.Product*")

Using the generated type with the generic version of SelectNodes, the Types extension can't be used, and no pages are returned. I assume because the inherited page types are not included.
        //returns nothing
        var products = tree.SelectNodes<Product>()
                           .OnSite("MyWebSite");

Based on this answer I tried a cast:
        var products = tree.SelectNodes()
            .OnSite("MyWebSite")
            .Types("My.Product*")
            .ToList()
            .Cast<Product>();

But the cast failed:

Unable to cast object of type 'CMS.Ecommerce.SKUTreeNode' to type 'CMS.DocumentEngine.Types.Product'.

I've also tried constructing the page type object from the results of the query:
        var products = tree.SelectNodes()
            .OnSite("MyWebSite")
            .Types("My.Product*")
            .ToList()
            .Select(x => TreeNode.New<Product>(null, x, tree))
            .ToList();

But the API doesn't like the class name mismatch:

Input class name 'My.ProductInheritingType is not consistent with the requested type 'CMS.DocumentEngine.Types.Product' which has class name 'My.Product'. To fix this, use correct class name or null as the input parameter.

Is there a way to use TreeProvider with my strongly typed page type, and retrieve pages which use inheriting page types?

A: I don't know if this is the best approach, but it's working at the moment. There were several problems to overcome:

*

*Querying all the inheriting types

*Ensuring the returned data included all the needed columns

*Mapping into the page type class

For the last item above, I couldn't find a way to get the Kentico API to initialize my base Product type if the document class name did not match. So I had to extend the generated class and call into a protected initialization method:
public partial class Product
{
    public void Initialize(IDataContainer data, TreeProvider treeProvider)
    {
        base.Initialize(this.ClassName, data, treeProvider);
    }
}

I could then construct and initialize this class in a LINQ statement that also includes querying for all the inheriting types of my base page type, with all their supporting data columns using the DocumentHelper API instead of the TreeProvider.
        var classId = DataClassInfoProvider.GetDataClassInfo("My.Product").ClassID;
        var productClasses = DataClassInfoProvider.GetClasses()
                                                  .WhereEquals("ClassInheritsFromClassID", classId)
                                                  .ToList();

        var products = DocumentHelper.GetDocuments()
                                       .OnSite("MyWebSite")
                                       .Types(productClasses.Select(x => x.ClassName).ToArray())
                                       .WithCoupledColumns()
                                       .ToList()
                                       .Select(x =>
                                       {
                                           var product = new Product();
                                           product.Initialize(x, tree);
                                           return product;
                                       })
                                       .ToList();

A: You can use the .WhereEquals("ClassInheritsFromClassID",TheMyProductClassID) to get all classes that inherit from that class.  That will probably be the best route.  Below should be approximately the right syntax.
int MyProductClassID = DataClassInfoProvider.GetClassInfo("My.Product").ClassID;
var AllInheritedClassIDs = DataClassInfoProvider.GetClasses().WhereEquals("ClassInheritsFromClassID", MyProductClassID).Select(x=> x.ClassID).ToList();

var products = tree.SelectNodes()
            .OnSite("MyWebSite")
            .WhereIn("NodeClassID", AllInheritedClassIDs);
            .ToList();


text:
Q: How to add custom Frame borders in Python Tkinter I'm building a GUI application with Tkinter. I am creating 9 buttons, 3 in each row. I want to make it so that the borders are drawn only between them, and there are no borders above and below. Can this be done with Tkinter?
    buttons_frame = [tk.Frame(
        self.root,
        highlightbackground="black",
        highlightcolor="black",
        highlightthickness=1,
        bd=0
    ) for i in range(9)]

    self.field_buttons = [tk.Button(
        buttons_frame[i],
        width=5,
        height=2,
        relief='flat',
        padx=1,
        font=('Arial', 20, 'bold'),
        command=lambda x=i: self.push(x)
    ) for i in range(9)]

    row, col = 1, 0
    for i in range(9):
        buttons_frame[i].grid(row=row, column=col, sticky='news')
        self.field_buttons[i].grid(row=row, column=col, sticky='news')
        col += 1
        if col == 3:
            row += 1
            col = 0

A: You can't do it with a single frame, but you can do it by placing a ttk.Separator between the rows and columns. Put the buttons in rows 0, 2, and 4, and in columns 0, 2, and 4. Then, put the separators in rows 1 and 3, and columns 1 and 3.
Start by creating a single frame for the buttons. Then, create the buttons as children of this frame. Then, use grid to distribute the buttons on every other row and in every other column.
Then, create four separators: two horizontal and two vertical. Put them in the rows and columns between the buttons and have them span all five rows and columns.
The following example illustrates the technique. I've added some exaggerated padding to make it a bit more obvious.
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

button_frame = tk.Frame(root, bd=0)
button_frame.pack(padx=10, pady=10)

field_buttons = [tk.Button(
    button_frame,
    width=5,
    height=2,
    relief='flat',
    padx=1,
    font=('Arial', 20, 'bold'),
) for i in range(9)]

rows = [0, 0, 0, 2, 2, 2, 4, 4, 4]
cols = [0, 2, 4, 0, 2, 4, 0, 2, 4]
for i in range(9):
    field_buttons[i].grid(row=rows[i], column=cols[i], sticky='news')

ttk.Separator(button_frame, orient="horizontal").grid(row=1, sticky="ew", columnspan=5, padx=10, pady=10)
ttk.Separator(button_frame, orient="horizontal").grid(row=3, sticky="ew", columnspan=5, padx=10, pady=10)
ttk.Separator(button_frame, orient="vertical").grid(row=0, column=1, sticky="ns", rowspan=5, padx=10, pady=10)
ttk.Separator(button_frame, orient="vertical").grid(row=0, column=3, sticky="ns", rowspan=5, padx=10, pady=10)

root.mainloop()


text:
Q: Substring-indexing in Oracle I just found that our current database design is a little inefficient according to the SELECT queries we perform the most. IBANs are positional coordinates, according to nation-specific formats.
Since we mostly perform JOINs and WHEREs on a precise substring of IBAN columns in some tables, my question is about assigning an index to the substring(s) of a column
Are we forced to add redundant and indexed columns to the table? Ie. add columns NATION_CODE, IBAN_CIN, IT_CIN, IT_ABI, IT_CAB, IT_ACCOUNT (where the IT_ fields are considered only for accounts starting in ITXX) each one with appropriate secondary indexing or is there any special kind of secondary index that can be applied only on a substring of a column?
The first solution could make the DB more complex since IBAN accounts are used all along the DBMS (and, obviously, I have no full control over design).
Thank you
[Edit] Typical query
SELECT * FROM DELEGATIONS WHERE SUBSTR(IBAN, 6, 5) IN (SELECT ABI FROM BANKS WHERE ANY_CONDITION)

Extracts all payment delegations where the target account belongs to any of the banks that match CONDITION. Should be changed to
SELECT * FROM DELEGATIONS WHERE SUBSTR(IBAN, 1, 2) = 'IT' AND SUBSTR(IBAN, 6, 5) IN (SELECT ABI FROM BANKS WHERE ANY_CONDITION)

to make sure that BBAN really holds the bank code in digits [6-11]

A: If you're using Oracle 11g, you could look at using virtual columns and then indexing those. This is pretty much equivalent to René's answer but might provide a bit more formality around the use of the data so that only the correct characters are used.
Virtual columns won't take up any additional space in the database, although any index you create on that virtual column will.

A: You're looking for a function based index:
create index ix_substring on TABLE (substr(COLUMN, 4, 9))


text:
Q: Trouble converting Excel to R Dates I have uploaded a CSV from Excel which has a column of dates.
The first 5 of these dates is the following:
dates <- c("25/09/2016","25/09/2016","25/09/2016","25/09/2016","25/09/2016", "25/09/2016")

When I use the following code:
as.Date(dates)

The result is
"0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20"

I've tried setting the origin to Excel's origin date:
as.Date(dates, origin = "1899-12-30")

But the result is still the same
"0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20" "0025-09-20"

Any ideas why it's not converting properly and what I should do?

A: With excel, you need to be very careful on the format under which the date is stored.
If your dates are in a character format, you need to use as.Date(dates, format = "%d/%m/%Y"). This will work for a character date in the format DD/MM/YYYY.
For others format of excel date, you need to modulate the format following the specifications gave in that link.
If your dates are in a numeric format, you need to use as.Date(dates, origin = "1899-12-30") for windows excel and as.Date(dates, origin = "1904-01-01") for mac excel.


text:
Q: Long landscape table: How to repeat the caption across multiple pages I have a four-page table in the landscape which displays correctly except the caption. I need to repeat the caption and header row on every page of the table
\documentclass{article}
\usepackage{longtable}
\usepackage{lscape}
\usepackage{booktabs}
\begin{document}
\begin{landscape}
\centering
\begin{longtable}{|p{1cm}|p{3cm}|p{8cm}|p{8cm}|}
    \caption{Caption I need it to repeat at every page} \\ \hline
    \textbf{Col 0}&\textbf{Col 1 } & \textbf{Col 2 } & \textbf{Col 3} \\
    1&BLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  \\ \hline
    2&BLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  \\ \hline
    \bottomrule
    \label{ch2:tab3}
\end{longtable}%
\end{landscape}
\end{document}

A: This code should work: load the caption package, and change the beginning of your table to:
\begin{longtable}{|p{1cm}|p{3cm}|p{8cm}|p{8cm}|}
\caption{Caption I need it to repeat at every page} \label{ch2:tab3}\\ \hline
\textbf{Col 0}&\textbf{Col 1 } & \textbf{Col 2 } & \textbf{Col 3} \\
\hline
\endfirsthead
\multicolumn{4}{c}{\tablename~\thetable Caption I need it to repeat at
every page (continued)} \\ \hline
    \textbf{Col 0}&\textbf{Col 1 } & \textbf{Col 2 } & \textbf{Col 3} \\
\hline
\endhead
    1&BLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  \\ \hline
    2&BLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  & BLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLABLA BLA  \\ \hline
    \bottomrule
\end{longtable}%


text:
Q: Would running NPC AI scripts be a good use case for web workers? I currently have a game with about 1500 non player characters all of which at the moment are running some variation of an AI script.  Right now this AI is really simple.  NPC's simply walk from location to location randomly.  This all happens in a game loop currently timed at 3 seconds as the game plays out in 3 second intervals.
Right now my AI doesn't seem to lock up the UI, but I imagine with more complexity or even more NPC's that it likely will start causing hiccups in the UI.  Is this a good use case for web workers?  My initial research tells me that I shouldn't create too many web workers so similar AI would likely be pooled together in a web worker of there own.
For anyone interested in actually looking at code this code would give you a good idea of what I'm doing although much of it has been rewritten at this time.  https://github.com/caimen/subfaction

A: So I did some tests and web workers do seem like a good use case for large amounts of NPC AI.  You can indeed make changes to the DOM with lot's of processing going on the background with web workers.  Not only that but they really are threads and actually do utilize processor cores at least in Chrome.  There are other considerations such as how many web workers to actually spawn, for that I found a nifty core estimator https://github.com/oftn-oswg/core-estimator
There is an excellent tool that is probably a bit out of date but still works.  It can benchmark about how many web workers is ideal for your computer and gives an interesting idea about there power.
http://pmav.eu/stuff/javascript-webworkers/
Of course if your AI is fairly simple and you aren't experiencing lag in the DOM there really is no need to overkill with this.


text:
Q: Can two people share two Dropbox accounts on a single Windows user account? my partner and i share a computer (windows 7) and have just one user profile, so we don't have to log in and out all the time, can we both install dropbox and have two different dropbox folders for two different dropbox accounts on the same user profile?

A: From the Dropbox Forums, by a Dropbox support person:

Note that in the vast majority of cases where people are asking about multiple accounts is best solved by Shared Folders. Unless there are two different people using the same computer, which different OS accounts is the proper way of handling it.
  Third party applications and hacks that are designed to get multiple Dropbox instances running at the same time for one user is not recommended, not only because they are completely unsupported (by the Dropbox team at least), but also because Dropbox is not meant to be utilized in such a manner. So the chance of issues is a lot higher than running Dropbox as per normal.

The answers to this question might also help you. Dropbox supports multiple accounts for multiple user accounts on the same machine, but one of the answers enables you to do this without requiring multiple users. It might be against the Terms of Service.

A: You could always use two instances of Dropbox Portable each with their own directory. I'm not sure whether you would need to quit one before using the other - you'd have to try it.


text: Q: Do mathematicians visualise what 4D would look like when they are working with abstract 4D concepts? I was wondering if mathematicians do truly have a sense of visualising what the fourth dimension would look like in general, such as the fourth dimension as found in hypercubes. I know that we, as 3D beings, cannot literally perceive 4D objects just as 2D objects can have no literal image of a 3D object. However, I do know that we can give the 2D objects a sense of whatvisualising 3D objects would look like if we introduce some abstract concepts, such as stereographical graphing, to them. So, my question is whether mathematicians have a rough concept of the visualisation of their work when they work with abstract concepts - in geometry - that involve dealing with the fourth dimension? And, I was also wondering if it would be useful to attempt to have an intuitive sense of 4D objects and planes before truly working with concepts involving the fourth dimension, because I fear I may end up like a machine lacking any fundamental intuition of their work and the concepts of their work which would truly irritate me as I always try proving concepts, intuitively understanding them, playing with them and even developing them further into more abstract concepts before I actually work the concept in problems.


text:
Q: Evaluation of keras model returns loss:0 and accuracy:0 I am trying to learn keras. As tutorial I used this https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/
Why does model.evaluate(X) returns loss:0 and accuracy:0?
# first neural network with keras make predictions
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
# load the dataset
dataset = loadtxt('pima-indians-diabetes.csv', delimiter=',')
# split into input (X) and output (y) variables
X = dataset[:,0:8]
y = dataset[:,8]
# define the keras model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# compile the keras model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit the keras model on the dataset
model.fit(X, y, epochs=150, batch_size=10)
# make class predictions with the model
predictions = (model.predict(X) > 0.5).astype(int)
# summarize the first 5 cases
for i in range(5):
    print('%s => %d (expected %d)' % (X[i].tolist(), predictions[i], y[i]))

print(model.evaluate(X))
print(model.predict(X[-5:]))

Terminal:

A: I forgot to add the target output to the model.evaluate().
print(model.evaluate(X, y))

This works fine!


text:
Q: is there a way to display a particular inline in a new page based on a condition? I need to display only one inline in a new page based on the condition like if the url has the parameter country_id then i need to display only one inline. Since I cannot make it in one ModelAdmin since the model admin has form validations in it, I used two modelAdmins for the same model. I have a readonly field called get_countries in CorporateConfig(admin which has form validations) and it will display a list of countries. If i click on a country based on that country id i need to display CorporateBrand which is an inline model to CorporateConfig on a new page(remember only that inline needs to be displayed).
class CorporateConfigurationAdmin(admin.ModelAdmin):
    form = CorporateConfigurationAdminForm
    inlines = [CorporateIncludeBrandAdmin, CorporateExcludeBrandAdmin,
               CorporateBrandsAdmin]

    def get_urls(self):
       from django.urls import path
       urls = super(CorporateConfigurationAdmin,self).get_urls()
       filter_url = [
           path('filter_brand/',self.admin_site.admin_view(self.brand_filter), name='brand-filter'),
        ]
       return filter_url + urls

    def brand_filter(self, request, obj=None):
        pass

    def get_countries(self, instance):
        country_list = '
'
        countries = Country.objects.all()
        print("countries", countries)
        for country in countries:
            url = reverse_lazy('admin:brand-filter')
            print("urls is",url)
            country_list += '
{country}
'.format(url=url, country=country.name,id=country.id)
        country_list+='
'
        return mark_safe(country_list)

    get_countries.short_description = 'Country Url'

Clicking on the link above should go to the custom url which is created by get_urls()

class BrandOrderFilter(CorporateConfiguration):
    class Meta:
        proxy = True

class CorporateInlineBaseAdmin(admin.TabularInline):
    def get_queryset(self, request):
        country = request.GET.get('country_id')
        qs = super(CorporateInlineBaseAdmin, self).get_queryset(request)
        if country:
            qs = qs.filter(brand__country=country)
        return qs

class CorporateBrandOrderFilterAdmin(CorporateInlineBaseAdmin):
    fields = ('brand', 'order_number',)
    raw_id_fields = ('brand',)
    ordering = ('order_number',)
    model = CorporateBrand

class BrandOrderFilteringAdmin(admin.ModelAdmin):
    inlines = [CorporateBrandOrderFilterAdmin,]

Now i can able to filter according to the countries but the fields from the model and validation is done by the form. So I created another admin and without using form i tried to display only that particular inline. unfortunately i am unable to do it. After 11 hours of hardwork im posting it here so that I can get some answers. Any help is greatly appreciated!!

A: I achieved this functionality by creating a new form and excluding the fields I needed and in the url I fetched the parameter request.GET.get('country_id'). If there was a country_id I am returning the new form with my new inline in a new page else return the form with all the inlines.


text:
Q: How to remove ArcGISTiledMapServiceLayer completely I have a problem related to "ArcGISTiledMapServiceLayer".
I have an ArcGISTiledMapServiceLayer map service, which I have added to Map object. This service work as BaseMap. Now I want to add another ArcGISTiledMapServiceLayer map service layer to the same Map object. Before adding the new layer, I just removed the previous tiled map service layer by using method objMap.removeAllLayers(). But this method only removes the layer not the extent and it create problem when I add a new layer.
So I want to remove completely the ArcGISTiledMapServiceLayer (layer, extent, scale etc.).
I have tried all the below methods

*

*objMap.removeAllLayers();

*objMap.removeLayer(objMap.getLayer('myLayerID'));
Any solution?

A: You should be able to call destroy on the current map instance then create a new esri/Map instance and load the new base map.
See: https://developers.arcgis.com/javascript/jsapi/map-amd.html#destroy
var map1 = new Map('map');
var basemap1 = new ArcGISTiledMapServiceLayer(url);
map1.addLayer(basemap1);
...
map1.destroy();
...
var map2 = new Map('map'); // note we load to the same html node
var basemap2 = new ArcGISTiledMapServiceLayer(url);
map2.addLayer(basemap2);


text:
Q: "Job title" vs. "job role" What is the difference between job title and job role?
For example, from the Google documentation on rich snippets:

title — The person's title (for example, Financial Manager)
role — The person's role (for example, Accountant)

I can't see a difference in meaning between the two.

A: A "job role" is a description of what a person does. A "job title" is a convenient name for a role.
For example: At my last job, my role was to write code that helped us be sure that our product worked as well as we thought it did. My title was Software Engineer, because it's (as noted in the comments on your post) short and to the point. People know what a Software Engineer does in general, without a long explanation.

A: A title is the name of a position within the company heirarchy.  "Production Engineer," "Maintenance Engineer," and "Reliability Engineer" are examples of job positions that various kinds of engineers (Chemical Engineers, Mechanical Engineers, etc., by their training) may be hired into.
A role is the part that is played within a specific work process within the company.  For example, during a large maintenance outage at a chemical plant, the Maintenance Engineer might be placed in charge of crane lifts, as a safety liaison; a Production Engineer may handle the plant shut-down and start-up logistics by interfacing with outside Utilities people--his role might be called "shutdown coordinator"; and a Reliability Engineer might fill the role of a "gatekeeper" that evaluates unplanned problems found during the planned work, to decide if the additional work should be accomplished during the outage or put off until later.
So a job title speaks to certain abilities and typical tasks based on training and experience, but also speaks to the level of the job within the organization (consider an Assistant Professor versus a Professor) and determines pay grade.  But a job role is the application of talents and abilities specific to a situation.  A person holding a job title can have different roles in different situations.


text:
Q: Ajax call to controller method not passing parameter I am trying to make an AJax call to a controller method the parameter is null no matter what I try.  I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it.  The code I have is...
Ajax Call
    var sguid = $(nTr).attr('id');
    $.ajax({
    url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
    type: 'POST',
    dataType: 'json',
    data: JSON.stringify({guid: sguid}),
    statusCode: {
        404: function() {
    alert("page not found");
        }
    },
    success: function (data) {
    //DO Something
    },
    error: function () {
        alert("error");
    }
});

Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
    List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
    Guid i = Guid.Parse(guid);
    ReportMethods reportingMethods = new ReportMethods();
    ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);

    DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
    List<DeviceApplication> da = new List<DeviceApplication>();
    if (ds != null)
    {
        da = ds.DeviceApplications;
    }

    return Json(da, JsonRequestBehavior.AllowGet);
}

The method is being hit its just guid is alway null.  sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?

A: Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.

A: Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{

A: Small changes needs to be done.
var sguid = $(nTr).attr('id');
    $.ajax({
    url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
    contentType: "application/json; charset=utf-8" ,//This is very important
    type: 'POST',
    dataType: 'json',
    Data: JSON. stringify ({guild: squid}),
    statusCode: {
        404: function() {
    alert("page not found");
        }
    },
    success: function (data) {
    //DO Something
    },
error: function () {
    alert("error");
}

});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax  Call.
:)


text:
Q: Safari column-count Bug So i found this Bug in Safari but cant find a solution to fix it.

.menu ul{
  column-count: 2;
}
.menu ul li{
     width: 257px;
    height: 35px;
}
.menu ul a{
  position: absolute;
  z-index: 999;
     width: 257px;
    height: 35px;
}

was

something

dtzdnj

was

something

dtzdnj

was

something

dtzdnj

so the left side is perfectly clickable but the right is not because the elements are not really on the right side.
This Image shows the problem while hovering an element which should be on the right side

A: This is the same but without position: absolute and z-index:999 for  the a elements and adding display:block to a element

.menu ul{
  column-count: 2;
}
.menu ul li{
     width: 257px;
     height: 35px;
}
.menu ul a{
 display:block;
     width: 257px;
    height: 35px;
}

 was

 something

 dtzdnj

 was

 something

 dtzdnj

 was

 something

 dtzdnj


text:
Q: jquery data attribute multiple values I have an issue with using multiple values in a data tag, and applying a filter based on the id of this. because its showing multiple ids in the data tag it wont show both ids.
Example at http://jsfiddle.net/rWhVN/
<script type="text/javascript">
        $(function () {
            $('#content').removeClass('nojs');
            $('.row').not('#q1').hide();
            $('select').on('change', function () {
                var question = $(this).parent().parent().attr('id');
                var answerID = $(this).children('option:selected').attr('id');
                var loadQuestion = $(this).children('option:selected').data('load');
                $('#' + question).addClass('answered');
                $('.row').not('.answered').hide();
                $('#' + loadQuestion).fadeIn();
                console.log(loadQuestion);
            });
        });
    </script>

<option id="q1a1" data-load="q2, q8">Answer 1</option>

Question one answer one should show question two and question eight.
Not sure how you split this out, so any help appreciated.

A: $('#' + loadQuestion) will be $('#q2, q8'), which will not be the seletor for #q2 and #q8.
You could do data-load="#q2, #q8", and then just do $(loadQuestion).
See the demo.
And if you can't change the data-load attribute, then you could do with:
$($.map(loadQuestion.split(/ *, */), function(el) {return '#'+el;}).join(',')).fadeIn();


text:
Q: Bootstrap Carousel - Load | Play | Pause I've spent some time and this one evades me.
What I'd like to do with the Carousel ...

*

*On page load no slide

*Press 'Play' button, side with interval 10000

*Press 'Pause' button and pause

*rinse and repeat Play & Pause

In js I'm using
// Play | Pause for carousel
$('#myCarousel').carousel({

});

$('#playButton').click(function () {
    $('#myCarousel').carousel('cycle');
});

$('#pauseButton').click(function () {
    $('#myCarousel').carousel('pause');
});

... but I'm just unable to get the proper effect as described. If I set the interval at the initial load it will kick off.

A: The carousel should be initialized with no interval (false). Then, set the interval when the "Play" btn is clicked. Try this...
$('#myCarousel').carousel({
  interval:false
});

$('#btnPause').click(function() {
  $('#myCarousel').carousel('pause');
});

$('#btnPlay').click(function() {
  $('#myCarousel').data('bs.carousel').options.interval=1000;
  $('#myCarousel').carousel('cycle');
});

Demo: http://bootply.com/113413


text:
Q: checking which tab is selected from another form From the original form form1, I can call this easily
this.tabControl1.SelectedTab.Text

But from form2, I cannot find equivalent method
(form1.Controls["tableLayoutPanel1"].Controls["tabControl1"] as TabControl)

does not have the SelectedTab method

A: Make the modifier on the TabControl's field Public, then you will be able to reference the tab control directly via the field with a reference to Form2.
It will look something like this after you have made the field public.
Form1 frm1 = <A reference to Form1 that you passed in to Form2 somehow>
frm1.TabControl1.SelectedTab.Text = "Changed Text!";


text: Q: Icons missing in 16.10 Desktop, taskbar, and search icons are missing on a freshly installed Ubuntu 16.10. possibly after switching to the high contrast theme. Reverting the theme or rebooting does not repair the missing icons. About half of the icons are missing and include standard Ubuntu icons, e.g., settings. How do I restore the icons?


text:
Q: How can I register ConEmu to run with DevCpp in Windows? I've installed ConEmu console, I've registered ConEmu as the default console for Windows system, but wxDev-C++ is still triggering the standard cmd.exe.
How can I bind ConEmu to DevCpp?
(The installed version of wxDev-C++ is 7.4.2.569, and the system is an old Windows XP).
EDIT1: Now I have attached DevCpp to ConEmu by Settings/Features/Integration", then "Force ConEmu as default terminal for console" (checkboxed), and in "List of hooked executables" I added devcpp.exe.
The result is that DevCpp triggers ConEmu, but the output of my test program is not shown.
The C program is the following:
// c:/cproj/experiment.c
#include <stdio.h>
int main(void) {
   for (long long i= 0; i<20; i++)
      printf("%d ",i);
   getchar();
   return 0;
}

In normal cmd.exe, it works well:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

When ConEmu is active, the ConEmu window has title "cmd.exe".
The ConEmu subwindow has title: "<1>.exe" and shows:
Microsoft Windows XP [Versión 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\cproj>

The "real" console shows exactly the same output.
EDIT2: DevCpp shows me the following information:
Compiler: Default GCC compiler
Executing  gcc.exe...
gcc.exe "C:\cproj\experiment.c" -o "nul"   -std=c99 -pedantic  -I"C:\Dev-Cpp\MinGW32\include"  -L"C:\Dev-Cpp\lib\wx\gcc_lib" -L"C:\Dev-Cpp\lib" -L"C:\Dev-Cpp\MinGW32\lib"
nul.exe: final close failed: File truncated
collect2: ld returned 1 exit status

Execution terminated

EDIT3 (I solved: see my answer below).

A: I have solved the problem.
In up-right corner of ConEmu there is an icon named BufferHeight mode....
This icon must be pressed in order to select BufferHeight mode is ON (scrolling is enabled).
Under this mode, the program runs as expected, showing the numbers 0 to 19.


text:
Q: Sitefinity Blog URL Format I am looking for guidance on an issue trying to change the blog url format to make the categories SEO friendly.
ISSUE
I am trying to have our blog categories URL changed from
https://example.com/blog/-in-category/categories/automotive
to
https://example.com/blog/automotive
Format: [domain]/[blogname]/[category]
I've added a custom blog provider and can access the categories with the above format, however, the hierarchical widget still shows the original url.
I did add an outbound rewrite rule that did update the widgets URLs to the correct format, however, it killed the Sitefinity backend (can't access Pages, Blog Post Content). Scriptresource.axd and Webresource.axd through a 404.
Here is the out bound rule..
<outboundRules>
               <rule name="Cat Rewrite Rule">
                    <match filterByTags="A" pattern="/blog/-in-category/categories/([^$]+)" />
                     <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
            <add input="{URL}" pattern="\.axd" negate="true" />
          </conditions>

                 <action type="Rewrite" value="/blog/{R:1}" />

                </rule>

              <preConditions>
                <preCondition name="IsHtml">
                  <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
                </preCondition>
              </preConditions>
 </outboundRules>

Errors from backend when trying to access the Pages:

Will a custom blog taxonomy evaluator solve what I am needing to accomplish (which I'm not sure how to do)?
Thanks for your help!

A: In your case, problem is that you forgot to use precondition. Working example is:
<outboundRules>
     <rule name="Cat Rewrite Rule" preCondition="IsHtml">
        <match filterByTags="A" pattern="/blog/-in-category/categories/([^$]+)" />
        <action type="Rewrite" value="/blog/{R:1}" />
     </rule>
     <preConditions>
         <preCondition name="IsHtml">
              <add input="{RESPONSE_CONTENT_TYPE}" pattern="^text/html"/>
         </preCondition>
     </preConditions>
</outboundRules>

P.S. But I am totally agree with @Veselin Vasilev, that cleaner approach is to build custom widget.
You can find source code of built-in widgets here:
Blogs: https://github.com/Sitefinity/feather-widgets/tree/master/Telerik.Sitefinity.Frontend.Blogs
Taxonomies: https://github.com/Sitefinity/feather-widgets/tree/master/Telerik.Sitefinity.Frontend.Taxonomies

A: I would probably create 2 custom MVC widgets that will handle this scenario:
First would be one that gets all categories and renders the links using the format you want, e.g. BlogCategories widget.
It will just generate a list of categories with links of the likes of "/blog/[category]"
Second widget would be a blog list controller that will have the category as a parameter and will get all blog posts that have that category.
It is a bit of work, but much cleaner than having url rewrite rules I think.


text:
Q: Only one time click on datepicker td is working When i select a date the below function just works one time:
$('.left').datepicker().find('td').click(function()
{
  alert("clicked");
});

What should i do so that if i click again on any td, this alert works?

A: The onSelect event fires whenever a data is selected, all the available events and methods are described in the documentation
$('.left').datepicker({
    onSelect : function() {
        alert('date selected');
    }
});

A: Try it (I've never tried it):
$('.left').each(function() {
    $(this).datepicker();
    $(this).find('td').click(function() {
        alert("clicked");
    });
});


text:
Q: ANOVA on list of lmList linear regressions I have a list of linear regressions generated using lmList (from lme4), similar to what was done here:
Now I want to compare these models using an ANOVA.
I've tried this:
anova(models_list)

but I get this:
Error in UseMethod("anova") :
no applicable method for 'anova' applied to an object of class" c('lmList4', 'list', 'vector')"

So then I tried this:
anova.lmlist(models_list)

but I get an error saying it can't find this function, even though it appears to be part of the base stats package.


text:
Q: Direct Access to CreateDIBitmap Bits [The final fix, which works unconditionally: use SetDIBitsToDevice, not BitBlt, to copy out the post-text-draw image data.  With this change, all occurrences of the problem are gone.]
I fixed the problem I'm having, but for the life of me I can't figure out why it occurred.

*

*Create a bitmap with CreateDIBitmap.  Get a pointer to the bitmap bits.

*Select the bitmap into a memory DC.

*Background fill the bitmap by directly writing the bitmap memory.

*TextOut.

*No text displays.

What fixed the problem: change item 3. from direct fill to a call to FillRect.  All is well, it works perfectly.
This is under Windows 10 but from what little I could find on the web, it spans all versions of Windows.  NO operations work on the bitmap - even calling FillRect - after the manual write.  No savvy, Kimosabe.  Elsewhere in the app, I even build gradient fills by directly writing to that bitmap memory and there is no problem.  But once TextOut is called after the manual fill, the bitmap is locked (effectively) and no further functions work on it - nor do any return an error.
I'm using a font with a 90 degree escapement.  Have not tried it with a "normal" font, 0 degree escapement.  DrawTextEx with DT_CALCRECT specifically states it only works on 0 degree escapement fonts so I had to use TextOut for this reason.
Very bizarre.
No, there were no stupid mistakes like using the same text color as the background color.  I've spent too long on this for that.  One option people have available is that the endless energy that would normally be spent destroying the question and/or the person who asked it could instead be used to write a few lines of code and try it for yourself.

A: Here's a function to make a bitmap. Don't pass a plain colour, pass a gradient fill, say going from white to pinkish.
Does it display correctly? If so, does the TextOut call on top of that work?
static HBITMAP MakeBitmap(unsigned char *rgba, int width, int height, VOID **buff)
{
    VOID *pvBits;          // pointer to DIB section
    HBITMAP answer;
    BITMAPINFO bmi;
    HDC hdc;
    int x, y;
    int red, green, blue, alpha;

    // setup bitmap info
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = width;
    bmi.bmiHeader.biHeight = height;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount = 32;         // four 8-bit components
    bmi.bmiHeader.biCompression = BI_RGB;
    bmi.bmiHeader.biSizeImage = width * height * 4;

    hdc = CreateCompatibleDC(GetDC(0));
    answer = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, &pvBits, NULL, 0x0);
    for (y = 0; y < height; y++)
    {
        for (x = 0; x < width; x++)
        {
            red = rgba[(y*width + x) * 4];
            green = rgba[(y*width + x) * 4 + 1];
            blue = rgba[(y*width + x) * 4 + 2];
            alpha = rgba[(y*width + x) * 4 + 3];
            red = (red * alpha) >> 8;
            green = (green * alpha) >> 8;
            blue = (blue * alpha) >> 8;
            ((UINT32 *)pvBits)[(height - y - 1) * width + x] = (alpha << 24) | (red << 16) | (green << 8) | blue;
        }
    }
    DeleteDC(hdc);

    *buff = pvBits;

    return answer;
}


text:
Q: Python web scraping and data mining i am doing web scraping on a wikipedia page. the code seems to be right, but i have a problem at the 11th line of the code.
code:
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
for row in film.findAll('tr'):
    states=row.findAll('th')
    cells=row.findAll('td')
    if len(cells==9):
        A.append(states[0].find(text=True))
        B.append(cells[0].find(text=True))
        C.append(cells[1].find(text=True))
        D.append(cells[2].find(text=True))
        E.append(cells[3].find(text=True))
        F.append(cells[4].find(text=True))

error:
TypeError                                 Traceback (most recent call last)
<ipython-input-38-bc871627aa75> in <module>()
      8     states=row.findAll('th')
      9     cells=row.findAll('td')
---> 10     if len(cells==9):
     11         A.append(states[0].find(text=True))
     12         B.append(cells[0].find(text=True))

TypeError: object of type 'bool' has no len()

A: Perhaps?
if(len(cells) == 9):
    whatever_code

A: You need to put the variable cells inside the brackets of the len() method. Since you have cells==9 inside the brackets the if statement is trying to find the length of a variable named 'cells==9' with no arguments.
It should look like this
if len(cells) == 9: