text:
Q: AS3 - getting variable named in order within a function I am sorry if this is a beginner's question.
I made some Arrays named like map01, map02 and so on... As you can see, I'm making a tile-based flash here. And I need to make a function that when you input a number like: createmap(1); it will get the variable map01 and use the information.
Can I do anything like: var temp:Array = Array(["map" + valueInput]);??
Please tell me if you need anything more.

A: First, instead of having variables with indices in their names, you should create an array of them. Here, an array of arrays.
So you just have to call var temp:Array = maps[valueInput] as Array;.
If you really don't want to do that and stick with your n variables, you can write
var index:String = valueInput.toString();
if (index.length == 1)
   index = "0" + index; //have the index on two digits "01", "02"
var temp:Array = this["map" + index];

Note that it will only work for your 99 first variables (oh God...)


text:
Q: date.toLocaleTimeString is not a function Am trying to print the date from script.js coming from mongodb but am getting the below error
Uncaught TypeError: date.toLocaleTimeString is not a function
function db_old_msgs(old_msg) {
    $('.chat-messages').append('' + old_msg.nick + ': ' + old_msg.msg +" "+FormatTime(old_msg.created) + "
");
}

function FormatTime(time, prefix = "") {
    var date = Date.parse(time);
    return ((typeof time != "undefined") ? prefix + date.toLocaleTimeString()  : "");
}

I tried the above without the function FormatTime like "+ old_msg.created.toLocaleTimeString() +" but I get the same error.
The time format that is received from db is 2021-12-16T13:22:01.600+00:00.
Dates are being displayed correctly which are coming from server.js
socket.broadcast.emit('msg', {from: users[socket.id],message: message, time:newMsg.created.toLocaleTimeString()})

Many thanks

A: The date was coming as string from the server so I had to convert it to date and then pass the function toLocaleTimeString()
function db_old_msgs(old_msg) {
    var dbtime=new Date(old_msg.created);
    var formattedDate = dbtime.toLocaleTimeString();
    $('.chat-messages').append('' + old_msg.nick + ': ' + old_msg.msg +" "+formattedDate + "
");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get the length of a file with a path longer than 260 characters? I am trying to find especially large files on a file share with deeply nested folders.  They aren't my folders, so I don't get to rearrange them.  The usual way to get the length of a file is:
string fullPath = "C:\path\file.ext";
FileInfo info = new FileInfo(fullPath);
long len = info.Length;

If the length of the path is greater than 260 characters, the FileInfo constructor throws a PathTooLongException.  I've read the Kim Hamilton blog entries on long file paths in .NET, so I know it can be done if I ditch the framework and do it all with Win32 API calls.  Is there a way to do it with the framework?
Kim Hamilton blog entries on long file paths in .NET:
Part 1
Part 2
Part 3

A: Check out the BCL Codeplex site, they have a future extension which might help you now:
http://bcl.codeplex.com/wikipage?title=Long%20Path

A: Windows does support paths longer than 260. However, this functionality is not exposed through .NET directly. To get the length of a file with path longer than 260, use the GetFileAttributesEx Windows API function which can be accessed in .NET through marshalling:
[StructLayout(LayoutKind.Sequential)]
public struct WIN32_FILE_ATTRIBUTE_DATA
{
    public FileAttributes dwFileAttributes;
    public FILETIME ftCreationTime;
    public FILETIME ftLastAccessTime;
    public FILETIME ftLastWriteTime;
    public uint nFileSizeHigh;
    public uint nFileSizeLow;
}

public enum GET_FILEEX_INFO_LEVELS {
    GetFileExInfoStandard,
    GetFileExMaxInfoLevel
}

public class MyClass
{
    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
    private static extern bool GetFileAttributesEx(string lpFileName,
          GET_FILEEX_INFO_LEVELS fInfoLevelId, out WIN32_FILE_ATTRIBUTE_DATA fileData);

    public static long GetFileLength(string path)
    {
         // Check path here

         WIN32_FILE_ATTRIBUTE_DATA fileData;

         // Append special suffix \\?\ to allow path lengths up to 32767
         path = "\\\\?\\" + path;

         if(!GetFileAttributesEx(path,
                 GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, out fileData))
         {
               throw new Win32Exception();
         }
         return (long)(((ulong)fileData.nFileSizeHigh << 32) +
                        (ulong)fileData.nFileSizeLow);
    }
}

A: Try out the Zeta Long Paths library: http://zetalongpaths.codeplex.com/

A: Works with the Microsoft Scripting Runtime COM reference
var fso = new Scripting.FileSystemObject();
double fileSize = fso.GetFile(path).Size;  // path is over 300 chars


text:
Q: Can't find a bin folder inside MySQL folder? So I have installed MySQL Workbench 8.0. When I start the program I see the following (shown in the picture below). I've looked for a way to solve this online, but I can't find MySQL network in Windows Services, and I don't even have the bin folder in MySQL folder.
Can somebody help me?


text:
Q: using params in $http.post doesn't work I want to deconstruct this url
this works
$http.post('http://mysrc:8080/calc?country=Usa&city=NewYork', {
          {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' }
});

to use params insted
this doesn't work
  $http.post('http://mysrv:8080/calc?', {
                    params: { country: "Usa", city: "NewYork" },
                    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==', }
                });

A: It's janky to use url params on a post. Traditionally data like you have goes in the body, commonly url encoded but in any case should match the header indicating the encoding.
See: HTTP POST with URL query parameters -- good idea or not?

A: I think you've misunderstood how $http.post works.  Try this:
 $http({params: { country: "Usa", city: "NewYork" },
        headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' }})
 $http.post('http://mysrv:8080/calc?');

A: This is the correct syntax from the docs.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

So for your example:
$http.post('/someUrl', null, {
                params: { country: "Usa", city: "NewYork" },
                headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' }
            });

But as others mentioned - since you don't post any data to the server, why use .post?

A: Use something like this.
$http({
    method: 'post',
    url : "https://myserver.com/api/v1/name",
    data : {
        fname : "Senthil",
        lname : "Kumar"
    }
    headers: {
        'Authorization': 'Basic token_hash'
    }
});


text:
Q: Installshield 2015 : displaying a simple installation report at end of installation process I'm using Installshield 2015  Premier Edition to create a MSI release from an Installscript MSI type project. The MSI installs several .NET application prerequisites and 5 .NET applications.
I'm kinda new to IS2015 and was wondering how to display an installation report at end of installation process to the end-user?
The installation report must sum up if all files were copied, if some prerequisites were correctly installed , and if scheduled tasks were installed.
This is the Installscript code which I use to launch the scheduled task creation :
//---------------------------------------------------------------------------
// OnFirstUIAfter
//
// The OnFirstUIAfter event called by the framework after the file transfer
// of the setup when the setup is running in first install mode. By default
// this event displays UI that informs the end user that the setup has been
// completed successfully.
//---------------------------------------------------------------------------
function OnFirstUIAfter()
   string szMessage, szTitle;
   number nResult;
begin

//if (SYSINFO.WINNT.bWinServer2003 && SYSINFO.WINNT.nServicePack > 1 ) then
if (SYSINFO.WINNT.bWinServer2003) then
    LaunchAppAndWait(TARGETDIR ^ "CreateSchedulingWinServer2003.bat", TARGETDIR, LAAW_OPTION_WAIT);
else
    LaunchAppAndWait(TARGETDIR ^ "CreateScheduling.bat", TARGETDIR, LAAW_OPTION_WAIT);
endif;

    LaunchAppAndWait(TARGETDIR ^ "RemoveSchedulingFile.bat", TARGETDIR, LAAW_OPTION_WAIT);
end;

Thanks you kindly,


text:
Q: Stanford Core NLP use tokensRegex Let's take the following"
client = CoreNLPClient(memory='1G', threads=1, annotators=['tokenize','ssplit','pos','lemma','ner','depparse'], timeout=1000)
ann = client.annotate('Wow a nice sentence here')
sentence = ann.sentence[0]

Then I process the tags, dependencies, etc. but I also want to use TokensRegex to extract specific words. I saw the answer using requests (here) however it seems odd to have to send another request (and do the tagging again) in order to use TokensRegex. Can we just use the already annotated sentence with TokensRegex?
Edit
I see that we can use client.tokensregex('Wow a nice sentence here', <pattern>) however this still has to send a request again I guess

A: There is a tokensregex annotator that you can place at the end of your pipeline that will run rules.
See here: https://stanfordnlp.github.io/CoreNLP/tokensregex.html


text:
Q: Right and left alignment in enumerated lists LaTex So for this piece of code:
\begin{enumerate}
\item[Komutativnost] $(a+b) = (b+a)$
\item[Asocijativnost] $a+(b+c) = (a+b)+c$
\item[Distributivnost] $a*(b+c) = (a*c) + (b*c)$
\end{enumerate}

I get this result:

How can I left/right align the item title and left/right align item text.

A: As usual, if you do not add your preamble, it is difficult to say what is right or wrong (MWE).
The enumerate environment is meant to produce numbered lists; if you want pointed lists or other effects you can use itemize or description instead (as in the comment by Alain).
I wrote to post your preamble because I've been doing LaTeX for 10 years now and I have no idea how \begin{description}[align=left] could ever work.
I will try to give you two "semantically decent" basic alternatives whose outputs differ almost only for indentation:
\documentclass{article}

\begin{document}

% first way:
\begin{description}
    \item[Komutativnost] $(a+b) = (b+a)$
    \item[Asocijativnost] $a+(b+c) = (a+b)+c$
    \item[Distributivnost] $a*(b+c) = (a*c) + (b*c)$
\end{description}

% second way:
\begin{itemize}
    \item[] Komutativnost $(a+b) = (b+a)$
    \item[] Asocijativnost $a+(b+c) = (a+b)+c$
    \item[] Distributivnost $a*(b+c) = (a*c) + (b*c)$
\end{itemize}

\end{document}

This article may also help understanding.


text:
Q: Replace all hyphens before the first bracket within a file I'm trying to use sed or perl to replace all hyphens which occur in a file before the first instance of );
So far I have the following which replaces all hyphens in my file but I can't get it to only match upto the first instance of ");".
perl -pi -e 's/[^.*);]?-/_/' 00-90.sql

Further information:
I'm trying to remove the invalid hyphens from create table SQL which has been generated, we have 1k+ files to get through but anything I hit it with replaces all hyphens.
Example of text to be cleansed:
CREATE TABLE e_00_90 (
Last_Name nvarchar(50),
  Initials nvarchar(3),
  Company_Division nvarchar(50),
  Status nvarchar(12),
  Ckeyword5 nvarchar(15),
  Value_of_Contract_-_Overh decimal(20,2)
);
insert into export_00_90 values ('Sample-One', 'R', 'Div 1', 'Expired', 'ANONYTR', 5000);
insert into export_00_90 values ('Sample Two', 'R', 'Div_2', 'Expired', 'WISHBONE', 13000);

I only need the Create Table block to have hyphens removed.

A: (?:(?!PAT).)* is to PAT as [^CHAR] is to CHAR, so
s/\G (?: (?! \); | - ) . )* \K - /_/xsg

Alternative:
s/\G (?: (?! \); ) [^-] )* \K - /_/xg

Fastest:
s/\G (?: [^)-]++ | \)(?!;) )* \K - /_/xg

A: With GNU sed:
sed -E ':a;s/^([^)]*)-([^)]*\);)/\1_\2/;ta;'

A: [EDIT]
With awk:
awk -v RS=');' -v ORS=');' '/^CREATE TABLE/{gsub("-","_")}1'

With perl:
perl -pe'BEGIN{$/=");"} /^CREATE TABLE/&&y/-/_/'

With sed:
sed '/^CREATE TABLE/{:;/);/!{N;b};y/-/_/;}'

The awk and perl ways are the same, they use a record separator );, check if this one starts with "CREATE TABLE" and translate each hyphen to an underscore.
The sed version isn't very different except that you need to build the text block yourself, appending each line until the );. (Note that this way assumes that there no more code after the ); in the same line):
{
  :  # define an empty label
  /);/! # if ); doesn't match
  {
    N # append a newline to the pattern space
    b # go to the label
  }
  y/-/_/ # translate
}

[OLD ANSWER: only works by line]
With sed:
sed -E ':;s/^(([^)-]|\)[^;-])*\)*)-/\1_/;t'

or with perl:
perl -pe's/.*?\);|.+/$&=~y|-|_|r/e'

(This way matches all until the first ); or the end of the string, then each hyphen in the match is translated to an underscore using y///)

A: I wouldn't try and tackle it with a magic regex, but rather:
#!/usr/bin/env perl
use strict;
use warnings;

while ( <DATA> ) {
   if ( m/CREATE TABLE/ .. /\);/ ) {
      s/-/_/g;
   }
   print;
}

__DATA__
CREATE TABLE e_00_90 (
Last_Name nvarchar(50),
  Initials nvarchar(3),
  Company_Division nvarchar(50),
  Status nvarchar(12),
  Ckeyword5 nvarchar(15),
  Value_of_Contract_-_Overh decimal(20,2)
);
insert into export_00_90 values ('Sample-One', 'R', 'Div 1', 'Expired', 'ANONYTR', 5000);
insert into export_00_90 values ('Sample Two', 'R', 'Div_2', 'Expired', 'WISHBONE', 13000);

The range operator lets you test if you're between two delimiters, and only apply the expression there.
As a one liner, this would be:
perl -pi -e 'm/CREATE TABLE/ .. /\);/ && s/-/_/g' 00-90.sql


text:
Q: What the difference between Cargo.toml and .cargo/config.toml I am learning to write a kernel by using Rust.
I added [dependencies] bootloader = "0.9.8" to .cargo/config.toml, but I got an error.
I forgot the specific error, but when I move [dependencies] bootloader = "0.9.8" to Cargo.toml and then run "cargo bootimage" on terminal, everything goes well.

A: Cargo.toml is where you put everything your project need. Dependencies, project details, project settings etc..
cargo/config.toml is a configuration file for Cargo. You usually don't need to touch it, and it usually uses more advanced things. It can be configured per project, although also globally. It sets for example what commands Cargo will run, what environment variables it will set, etc..
All details about both are in the documentation - Cargo.toml, config.toml.


text:
Q: How to define a subclass of Recycler.Adapter I need to define a custom RecyclerView and RecyclerView.Adapter. RecyclerView is OK, but I don't know how to define a subclass of RecyclerView.Adapter because of it's Generic type.
This my code, and Android Studio shows Unexpected bound.
public static abstract class Adapter<VH> extends RecyclerView.Adapter<VH extends RecyclerView.ViewHolder>

A: You should define it like this
public static abstract class Adapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
}

the structure is like this
class ABC<-definition-> extends DEF<-usage->
It is because the definition has to be done in quote following the class which you are declaring. In the second quote, you only use it.
The meaning of the whole statement is the VH is definited to be a subclass of RecyclerView.ViewHolder, and the Adapter<VH> is a subclass of RecyclerView.Adapter<VH>. Because  VH has the right superclass, so the whole statement would now be valid.


text:
Q: Swift - Return type of struct parameters without default values I'm very new in Swift so i might be missing some basics.
I have struct:
    struct MyStruct {
        var a: Int
        var b: String
        var c: Bool

        init() {
          a: Int = 1,
          b: String? = "",
          c: Bool? = false
        }
    }

and function, that should iterate through given struct properties and return their types in json:
func structProps(){
  let elm = MyStruct()
  let mirror = Mirror(reflecting: elm)
  var exampleDict: [String: String] = [:]
  for child in mirror.children  {
      exampleDict[child.label!] = String(describing:type(of: child.value)) as String
  }
  if let theJSONData = try? JSONSerialization.data(
      withJSONObject: exampleDict,
      options: []) {
      let theJSONText = String(data: theJSONData, encoding: .ascii)
  }
}

it kinda return what i need:
JSON string = {"a":"Int","b":"String","c":"Bool"}

Because i'm having a lot of structs and i want to export json from all of them, i'm wondering if there is a way to have generic initializer. Without passing default values.
It means without
init() {
 a: Int = 1,
 b: String? = "",
 c: Bool? = false
}

A: If I understand correctly , you can create a base protocol and add as an extension to your structures like
protocol BaseFunction {
    func getElements() -> [String : String]
    func getDict() -> String
}

extension BaseFunction {
  func getElements() -> [String : String] {
    let mirror = Mirror(reflecting: self)
    let propertiesRemoveNil = mirror.children.filter({!(($0.value as AnyObject) is NSNull)})
    let properties = propertiesRemoveNil.compactMap({$0.label})

    var types = [String]()
    _ = mirror.children.forEach({
        types.append(String(describing:type(of: $0.value)))
    })

    return Dictionary(uniqueKeysWithValues: zip(properties, types))

  }
    func getDict() -> String{
    if let theJSONData = try? JSONSerialization.data(
      withJSONObject: getElements(),
      options: []) {

        let theJSONText = String(data: theJSONData, encoding: .ascii)
        return theJSONText ?? ""

    }
    return ""
  }

}

And usage :
func structProps(){
    let elm = MyStruct()
    print(elm.getDict())

}

OUTPUT :
{"a":"Int","b":"String","c":"Bool"}

A: I was going to write a comment about using a protocol but I thought it would be easier to understand as an answer with some code.
To make the usage more generic so you don't need specific code for each type of struct you should use a protocol. Instead of having an init that might clash with already existing init in the struct I prefer a static method that returns a new object, also known as a factory method
protocol PropertyExtract {
    static func createEmpty() -> PropertyExtract
}

Then we can make use of the default init for the struct or any supplied to create an object with some initial values by letting the struct conform to the protocol in an extension
extension MyStruct: PropertyExtract {
    static func createEmpty() -> PropertyExtract {
        MyStruct(a: 0, b: "", c: false)
    }
}

And instead of hardcoding or passing a specific type of object to the encoding function we pass the type of it
func structProps(for structType: PropertyExtract.Type)

and use the protocol method to get an instance of the type
let object = structType.createEmpty()

The whole function (with some additional changes)
func structProps(for structType: PropertyExtract.Type) -> String? {
    let object = structType.createEmpty()
    let mirror = Mirror(reflecting: object)

    let exampleDict = mirror.children.reduce(into: [String:String]()) {
        guard let label = $1.label else { return }
        $0[label] = String(describing:type(of: $1.value))
    }

    if let data = try? JSONEncoder().encode(exampleDict) {
         return String(data: data, encoding: .utf8)
    }

    return nil
}

And this is then called with the type of the struct
let jsonString = structProps(for: MyStruct.self)

A: According to Creating a Swift Runtime Library, there is a way to access meta data types without initializer.
Solution for what i was asking for is possible with Runtime library.

A: Mirror(reflecting:) expects an instance of a type and not a type itself, ref.
One idea is to have a generic function that works with all types conforming to a protocol that provides an empty init. Something like:
protocol EmptyInitializable {
  init()
}

struct StructOne {
  let a: Bool
  let b: String
}

struct StructTwo {
  let c: Int
  let d: Float
}

extension StructOne: EmptyInitializable {
  init() {
    a = false
    b = ""
  }
}

extension StructTwo: EmptyInitializable {
  init() {
    c = 1
    d = 1.0
  }
}

func print(subject: EmptyInitializable) -> String? {
  let dictionary = Dictionary(uniqueKeysWithValues:
    Mirror(reflecting: subject).children.map {
      ($0.label!, String(describing: type(of: $0.value)))
    }
  )
  return (try? JSONSerialization.data(withJSONObject: dictionary)).flatMap {
    String(data: $0, encoding: .utf8)
  }
}

print(subject: StructOne()) // "{"a":"Bool","b":"String"}"
print(subject: StructTwo()) // "{"d":"Float","c":"Int"}"

You still have to implement the empty init and assign some values and I'm afraid there's no way currently to avoid that.


text:
Q: Querying result from mongoose using dynamic model.find I need to find the results of a query with mongoose find({}) method in Node.js with a variable containing model name.
var adSchema     =  new Schema({ schema defination });
var Ad           =  mongoose.model('Ad', adSchema);
var variableName = 'Ad';
variableName.find({}).exec(function (err, adObj) {});

Is it possible or not?
Thanks in advance

A: You should be able to do that when calling model with just the name like so
mongoose.model('Ad').find({}).exec(function (err, adObj) {});

See here for the corresponding part of the official docs

A: Try this:
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    var anySchema = new Schema({
      fieldname:  String
    });
    var Test = mongoose.model('Test', anySchema);
    Test.find({}).exec(function(err,result){});


text:
Q: Best way to securely store chat logs on server A chat app I'm developing requires storing the chat history on the server. Whats the best way to securely store this? I do not want to store plain-text chat logs in a table.
My initial thought was storing them encrypted based on the *users password, however if the user forgets his password, whats the best way to handle that? Since I have no idea what the password is to decrypt and re-encrypt with the new password.
Another solution was encrypt everything with a public key, and keep the private key stored on a separate machine (and in local memory for that server) and fetch it when its needed to decrypt and grab the full chat history.
Any help or case-studies would be awesome.
*added to avoid confusion

A: Because if the DB is stolen, you want to protect against these:

*

*Avoid plain text messages.

*The keys can't be stored in the same database.

*You don't want a single key, because if that is guessed, then they unlock everything.

*You don't want the key keys tied to information provided by the user (especially if it is easily guessable or can change/forgotten).

So if you have the budget, I would use a hardware based solution. This would provide the necessary separation and supply you with good keys, that aren't stored on the file system or database, and will be stored securely themselves. You can start with a single card (keeping everything on the same physical server) or scale out to a rack-mounted box if necessary.


text:
Q: celery-django can't find settings I have a Django project that uses Celery for running asynchronous tasks.  I'm doing my development on a Windows XP machine.
Starting my Django server (python manage.py runserver 80) works fine, but attempting to start the Celery Daemon (python manage.py celeryd start) fails with the following error:
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings
sys.path includes 'C:\development\SpaceCorps\src', so I'm not sure why it can't find this module.
Here's the full output from starting the daemon:
C:\development\SpaceCorps\src>python manage.py celeryd start
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mcelery@mike-laptop v2.0.1 is starting.?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mC:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\bin\celeryd.py:206: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in a production environment!
  warnings.warn("Using settings.DEBUG leads to a memory leak, "?[0m
[2010-07-23 18:29:31,456: WARNING/MainProcess] ?[1;33mConfiguration ->
    . broker -> amqp://guest@localhost:5672/
    . queues ->
    . celery -> exchange:celery (direct) binding:celery
    . concurrency -> 2
    . loader -> djcelery.loaders.DjangoLoader
    . logfile -> [stderr]@WARNING
    . events -> OFF
    . beat -> OFF?[0m
[2010-07-23 18:29:31,706: WARNING/MainProcess] ?[1;33mcelery@mike-laptop has started.?[0m
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
    self = load(from_parent)
  File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
    return Unpickler(file).load()
  File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
Traceback (most recent call last):
  File "<string>", line 1, in <module>
    dispatch[key](self)
  File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
  File "C:\Program Files\Python26\lib\multiprocessing\forking.py", line 342, in main
    self = load(from_parent)
  File "C:\Program Files\Python26\lib\pickle.py", line 1370, in load
    klass = self.find_class(module, name)
  File "C:\Program Files\Python26\lib\pickle.py", line 1124, in find_class
    return Unpickler(file).load()
  File "C:\Program Files\Python26\lib\pickle.py", line 858, in load
    dispatch[key](self)
  File "C:\Program Files\Python26\lib\pickle.py", line 1090, in load_global
    __import__(module)
  File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\concurrency\processes\__init__.py", line 7, in <module>
    from celery import log
  File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\log.py", line 8, in <module>
    from celery import conf
  File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 118, in <module>
    ALWAYS_EAGER = _get("CELERY_ALWAYS_EAGER")
  File "C:\Program Files\Python26\lib\site-packages\celery-2.0.1-py2.6.egg\celery\conf.py", line 109, in _get
    value = getattr(settings, alias)
  File "c:\development\django\django\utils\functional.py", line 276, in __getattr__
    self._setup()
  File "c:\development\django\django\conf\__init__.py", line 40, in _setup
    self._wrapped = Settings(settings_module)
  File "c:\development\django\django\conf\__init__.py", line 75, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'src.settings' (Is it on sys.path? Does it have syntax errors?): No module named src.settings

A: Apparently this is a problem with running Celery on Windows.  Using the --settings argument ala python manage.py celeryd start --settings=settings did the trick.

A: sys.path must include 'C:\development\SpaceCorps' not 'C:\development\SpaceCorps\src',
because he is looking for src.settings, not just settings.


text:
Q: How to make Firefox Developer Tools display FirePHP messages within console? I decided to try working with the Firefox Developer Edition. I am writing PHP code for a Joomla site and use Firebug & FirePHP to send data to the console.
While that works fine with the standard Firefox (36.0.4), I get no output with the Developer Edition (38.0a2).
Am I missing something? Should that work OK?

A: Actually after digging a bit around, found that Firefox Developer Edition already has an integrated server side logging. You can implement it via Chrome Logger, which has also a PHP extension available.
Besides that you can try it with the newest version of FirePHP, but as far as I can tell it works only with Firebug 2.x, which doesn't work while Firefox is working in multi-process mode.
I got the server loggin console working without an issue with Chrome Logger instead of the FirePHP port. And with Firebug.next I can't make it work.

A: On http://firephp.org/ it says "Coming Soon: FirePHP Extension for Firebug.Next (Firebug 3.0) & Firefox Developer Tools" but no date is given.

A: FirePHP for Firefox Developer Tools has now been released :
https://github.com/firephp/firephp-for-firefox-devtools

A: Take a look at QuantumPHP.  Browser add-on:
https://addons.mozilla.org/en-US/firefox/addon/quantumphp/
FirePHP fork that works with the above add-on:
composer require frankforte/quantumphp

If you do not use composer, you can also follow the instructions here:
https://packagist.org/packages/frankforte/quantumphp


text:
Q: How to move tickets to next sprint in Jira to have correct time counting? Suppose we have a ticket with estimation of 4 units and this ticket was half done in one sprint and moved to next one.
Will it make difference, when we did re-estimation?
One option is to change estimation before sprint closed and then to move ticket and another option is to close sprint, move ticket and the re-estimate it.
What is correct way? Suppose 2 of 4 units were spent and we want to account it in a report.

Regard the following burndown report of 2-week spring

Apparently it goes down once ticket is completed. But suppose we have long ticket and the end of the sprint. Suppose it was not done this sprint and was moved to next one. How will it count.

A: Your estimation for that ticket did not change and you do not need to reestimate. You only are only moving the ticket to another sprint. If you want to include that 2 units of work in your reports, then it is a matter of your timesheet application, not the estimation or the sprint itself.


text:
Q: Opening another android browser from chrome (android) via href I have a website which needs to play flash, unfortunately, android chrome does not support playing flash. As a solution to this, I need to open the URL to another browser which is dolphin browser that has a built in flash player. The question now is how am i going the launch the dolphin browser and pass the url? I have tried using Android Intents but still no luck. I also have this line of code:
<a href="intent://my_url_to_open#Intent;scheme=http;package=mobi.mgeek.TunnyBrowser;action:ACTION_VIEW;category=android.intent.category.BROWSABLE;end"

What am I missing? Or did I make it the wrong way?

A: Use this code:
String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

Note that, when you will fire up this intent, there should be an option to chose browsers. If you already set a default browser, then you have to remove that default browser.


text:
Q: Is it an implementation of a stateful mechanism for Rest API authentication? In many articles about Rest API's best practices, it is recommended to not depend upon sessions on server side since it leads to a stateful mechanism.
I currently use Play 2.2 framework, with a mechanism that store the data about logged in user in the Play cache (temporary persistent so).
When the user wants to authenticate, it calls a dedicated API that grabs its credentials and if valid, server generates a cookie that will be sent to him. This cookie contains a reference id of the user's data in the Play's cache.
Then, each time a user calls an API requiring user authentication, server grabs the user cookie (if any), asks for the cache and checks in there whether user is well already authenticated regarding the validation duration.
Here a little sample:
def myApi = userAuthenticatorRequest.securedAction {    //user has to be already logged in
    implicit request =>
      //do something
  }

Should I leave from this solution in order to be compliant with best practices, or should I keep it?
Is it really considered as a stateful mechanism?
If I understand, this is stateful since a call to a secured API required actually two calls:

*

*authentication api

*secured api

while a stateless would authenticate user directly in the secured api, and thus would be totally independent of any context. Of course, user would have to sent each time its credentials (or API key)

A:
If I understand, this is stateful since a call to a secured API required actually two calls

This is stateful because the information "user X has been authenticated at time T" is maintained on the server side.

Of course, user would have to sent each time its credentials (or API key)

A user can also sign each request to attest her identity, thus proving the server she can access some private key.


text:
Q: Capture variable when exception occurs I have this error:
[Wed Jul 25 15:48:09 2012] [error] [client 50.xxx.xxx.xxx] PHP Fatal error: Call to a member function getSource() on a non-object in /var/www/magento/app/code/core/Mage/Catalog/Model/Product.php on line 1389
In this function:
/**
 * Get attribute text by its code
 *
 * @param $attributeCode Code of the attribute
 * @return string
 */
public function getAttributeText($attributeCode)
{
    return $this->getResource()
       ->getAttribute($attributeCode)
            ->getSource()
                ->getOptionText($this->getData($attributeCode));
}

And I want to log the $attributeCode value whenever the error occurs. So I change the function to this:
public function getAttributeText($attributeCode)
{
    try {
        return $this->getResource()
           ->getAttribute($attributeCode)
                ->getSource()
                    ->getOptionText($this->getData($attributeCode));
    } catch (Exception $e) {
        Mage::log($attributeCode);
        throw($e);
    }
}

…and restart Apache, yet nothing shows up in the server.log. If I comment out the throw($e), the exception still gets thrown.
./lib/Zend/Rest/Server.php has set_exception_handler(array($this, "fault"));
But please tell me php doesn't ignore all manual exception handling once you set that somewhere. Because that would be crazy.
Any idea how I can capture the $attributeCode only when the exception happens?

A: Try
$attributes = $this->getResource()->getAttribute($attributeCode);
if (!empty($attributes)) {
    return $attributes->getSource()->getOptionText($this->getData($attributeCode));
} else {
    Mage::log($attributeCode);
    throw new InvalidArgumentException('bla bla');
}

// I do not know what is returned by getAttribute($attributeCode); so instead of empty() you can use is_null(), isset()

A: For debugging purposes only, I would do this:
if (!is_object($this->getResource()->getAttribute($attributeCode)) {
    var_dump($attributeCode);
    exit();
}


text:
Q: "Unreachable code" Java Hi i try to make program who when will be compiled print X and Id arrays but i have a problem when i try add static int. I made this like on tutorial but it can't compile. Do you have any suggest?
class SetCord
{
   double x;
   double y;
   private  int Id;
   private static int NextId;

   public SetCord(double a, double b)
   {
      x=a;
      y=b;
   }

   public double getX()
   {
      return x;
      Id=NextId;
      NextId++;
   }

   public double getY()
   {
      return y;
      Id=NextId;
      NextId++;
   }

   public int getId()
   {
      return Id;
   }
}

class Test
{

   public static void main(String args[])
   {
      SetCord[] teste = new SetCord[3];
      teste[0] = new SetCord(3, 5);
      teste[1] = new SetCord(5, 5);
      teste[2] = new SetCord(1, 2);

      for(SetCord x:teste)
      {
         System.out.println("give x" +  x.getX());
         System.out.println("give id" +  x.getId());
      }
   }

   static
   {
      NextId=1;
   }
}

Thanks!

A: There shouldn't be any statements post return in your method. Return should be the last statement of your method
LIKE THIS:
public double getX()
{
    Id=SetCord.NextId;
    SetCord.NextId++;
    return x;
}
public double getY()
{
    Id=SetCord.NextId;
    SetCord.NextId++;
    return y;
}

A: Statements after return cannot be reachable. For ex
public double getY()
{
    return y;
    Id=NextId;
    NextId++;
}

What ever business logic you want to do, do before the method return.
You want to do ?
public double getY()
{
    Id=NextId;
    NextId++;
   return y;
}


text: Q: A question about matrices. I have never learned matrices in my school. I'm currently about to be a junior in  high school. Through videos I know how to add and multiplying matrices. However I often see people relating them with vectors and doing some pretty interesting things. As far as I am concerned there just like a list of numbers, with a purpose I cannot see. What can you tell me about matrices.


text:
Q: Pandas: Can I filter a dataframe to get only rows with a 50% difference between each other? The following is a sample dataframe. My actual dataset has 30k rows.
df = pd.DataFrame({'Account': [30, 30, 30, 30, 30, 30, 30, 40, 40, 40],
                   'Start': [2, 2, 2, 2, 2, 3, 3, 1, 1, 1],
                   'Amount' : [500, 600, 800, 200, 700, 10, 800, 10, 50, 70]})

   Account Start  Amount
0       30     2     500
1       30     2     600
2       30     2     800
3       30     2     200
4       30     2     700
5       30     3      10
6       30     3     800
7       40     1      10
8       40     1      50
9       40     1      70

I want to find all rows (grouped by Account and Start) where Amount in row 1 differs from Amount in row 2 by ± 50%. I am expecting the result to look like this.
   Account Start  Amount
0       30     2     500
1                    600
2                    800
8       40     1      50
9                     70

Row 3 is excluded as 200 in row 3 is less than 50% of the amount in row 2 as well as the amount in row 3.
Row 4 is excluded as it is the last element in start = 2 and the previous row is also excluded.
Similarly, Row 5 and 6 are excluded.
Row 7 is excluded as 10 is less than 50% of the amount in row 8.
PS: In the final dataset, each group of Account and Start should have at least 4 rows.
Is there a way to do this efficiently?

A: We use pct_change, checking if it's between -50% and 50%. Because you want pairs of rows we need to check this mask or the shifted mask (shifting in the opposite direction in which we calculated the pct_change). We'll apply this function to each group separately.
def keep_within_pct(gp, shift=1, pcts=(-0.5, 0.5)):
    m = gp['Amount'].pct_change(-shift).between(*pcts)
    return gp[m | m.shift(shift).fillna(False)]

df.groupby(['Account', 'Start'], group_keys=False).apply(keep_within_pct)

   Account  Start  Amount
0       30      2     500
1       30      2     600
2       30      2     800
8       40      1      50
9       40      1      70


text:
Q: Inserir array em um banco de dados usando PHP No site que estou criando eu tenho um formulário onde as pessoas podem adicionar vários tópicos. O meu problema está no momento onde é criado um segundo ou mais tópicos pois só o primeiro vai para o banco e eu não consigo fazer os demais serem inseridos.
O código que eu to fazendo é esse aqui:

<input id="topico" type="text" name="campo[]" class="validate" required  >
Adicione pelo menos um tópico

    add

O PHP:
$nm_reuniao = $_POST['nm_reuniao'];
$dt_reuniao = $_POST['dt_reuniao'];
$nm_topico = $_POST['campo[]'];
$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador) VALUES ('$nm_reuniao','$dt_reuniao', '$logado')";

$insert = mysql_query($query,$connect);

if($insert){
  echo"";
}else{
  echo"";
}

A: Os problemas encontrados no seu código são:

*

*Errado $nm_topico = $_POST['campo[]'];
Correto $nm_topico = $_POST['campo'];

*Os values da declaração INSERT  ('$nm_reuniao','$dt_reuniao', '$logado')";
Ao invés de $logado acho que deveria ser $nm_topico

*Mas mesmo sendo $nm_topico iria inserir somente uma linha na tabela
Esqueça essas correções que a solução proposta não vai utilizá-las.

Uma única declaração INSERT ... VALUES pode adicionar múltiplos registros em uma tabela se você fornecer múltiplas listas de valores. Para fazer isso, forneça uma lista de valores entre parêntesis para cada registro e separe as listas com virgulas.

Por exemplo:
INSERT INTO PESSOAS (nome, sobrenome)
VALUES ('Paula','Cavalcante'),('Leo','Caracciolo'),('dvd','SemSobrenome')

A declaração mostrada cria três registros na tabela pessoas, atribuindo às colunas nome e sobrenome de cada registro os valores listados. A coluna id não é listada explicitamente, de modo que o MySQL atribui um valor da sequência para essa coluna em cada registro.
Uma declaração INSERT de múltiplas linhas é logicamente equivalente a um conjunto de declarações de única linha individuais. Entretanto, a declaração de múltiplas linhas é mais eficiente porque o servidor pode processar todas as linhas de uma vez em vez de em operações separadas. Quando você tiver muitos registros a adicionar, declarações de múltiplas linhas fornecem um desempenho melhor e reduzem a carga do servidor. Por outro lado, tais declarações são mais prováveis de alcançar o tamanho máximo do buffer de comunicação usado para transmitir informações para o servidor (esse tamanho é controlado pela variável max_allowed_packet, que possui um valor padrão de 1MB).
Código PHP
$nm_reuniao = $_POST['nm_reuniao'];
$dt_reuniao = $_POST['dt_reuniao'];

//Use o foreach para gerar a lista de valores
foreach($_POST['campo'] AS $indice => $valor) {
  $values .= " ('$nm_reuniao', '$dt_reuniao', '$valor'),";
}
//retira a ultima virgula
$values=substr($values, 0, -1);

$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador`) VALUES $values";

$insert = mysql_query($query,$connect);

Talvez fosse como abaixo indicado, não sei, sua pergunta não está bastante clara

$values .= " ('$nm_reuniao', '$dt_reuniao','$logado','$valor'),";

$values=substr($values, 0, -1);

$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador,nm_topico) VALUES $values";

A: Faça da seguinte forma:
$topicos = $_POST['campo'];
$query = "INSERT INTO reuniao (nm_reuniao,dt_reuniao,nm_criador,nm_topico) VALUES ('$nm_reuniao','$dt_reuniao', '$logado','$nm_topico')";
foreach ($topicos as $nm_topico) {
  $insert = mysql_query($query,$connect);
}

Sua variável $nm_topico recebe um array com as informações passadas pelo seu formulário com name='campo[]', então para que seja inseridas todas as linhas é necessário fazer uma estrutura de repetição inserindo linha a linha.


text:
Q: AE.net.Mail, How to move mail to a new folder in outlook How to move mail to a new folder in outlook?
My code:
using (ImapClient ic = new ImapClient(
                             imapAddr,
                             myEmailID,
                             myPasswd,
                             ImapClient.AuthMethods.Login,
                             portNo,
                             secureConn))
{
     ic.SelectMailbox("INBOX");
     bool headersOnly = false;
     Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), headersOnly);
     foreach (Lazy<MailMessage> message in messages)
     {
       MailMessage m = message.Value;
     }
}

I try Google it but I can not find it .
Any suggestions are highly appreciated.

A: to move a message to another folder do this:
ic.MoveMessage(message.Uid, "some existing folder");

The uid is the unique identifiier for the mailmessage. I assume it maps to the message-id as described in RFC for Internet Message Format. Or otherwise to the UNIQUEID in the IMAP protocol.
to create a new folder use the this method:
ic.CreateMailbox("new mailbox name");

To send emails use an SmtpClient, like the one that is supplied in the .net framework:
        using(SmtpClient client = new SmtpClient("your smtp server.com"))
        {
            client.Send("from@example.com",
                        "to@example.com",
                        "subject",
                        "Hello World");
        }


text:
Q: Digital clock in status bar in python 3 and tkinter I want to put this digital clock:
import sys
from tkinter import *
import time

root = Tk()
time1 = ''
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.pack(fill=BOTH, expand=1)

def tick():
    global time1
    # get the current local time from the PC
    time2 = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    if time2 != time1:
        time1 = time2
        clock.config(text=time2)
        # calls itself every 200 milliseconds
        # to update the time display as needed
        # could use >200 ms, but display gets jerky
    clock.after(200, tick)

tick()
root.mainloop(  )

in this status bar:
status = Label(mGui, text="v1.0", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)

Is there a way to do that?
Thanks everyone who want to help, I appreciate it :)

A: What is with the if statement? It is unnecessary as the clock.after statement is calling tick() directly within the clock.after() function, to which updates your time string.
import sys
from Tkinter import *
import time

def tick():
    # get the current local time from the PC
    time_string = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    clock.config(text=time_string)
    clock.after(200, tick)

root = Tk()
clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.grid(row=0, column=1)
tick()
root.mainloop()

Also, remember to use Tkinter (Capital T) for Python 2.7 and tkinter (lowercase t) for Python 3.0.

A: Tkinter noob here, but i don't think you can put the clock label inside the status label. However you can put them side by side:
import sys
from tkinter import *
import time

def tick():
    global time1
    # get the current local time from the PC
    time2 = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    if time2 != time1:
        time1 = time2
        clock.config(text=time2)
        # calls itself every 200 milliseconds
        # to update the time display as needed
        # could use >200 ms, but display gets jerky
    clock.after(200, tick)

root = Tk()
time1 = ''

status = Label(root, text="v1.0", bd=1, relief=SUNKEN, anchor=W)
status.grid(row=0, column=0)

clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.grid(row=0, column=1)

tick()
root.mainloop()

A: Normally, I make a statusbar out of a frame, and then pack whatever things I want to display in that frame. For example, your clock could be packed on the right side, and your status label could be packed on the left. Then you can put the whole statusbar frame at the bottom of your GUI.
Normally I prefer to give examples using an object-oriented style, but here's an example adapted from the code in your question:
import sys
from tkinter import *
import time

root = Tk()

statusbar = Frame(root)
statusbar.pack(side="bottom", fill="x", expand=False)

time1 = ''
clock = Label(root, font=('times', 20, 'bold'), bg='green')

def tick():
    global time1
    # get the current local time from the PC
    time2 = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    if time2 != time1:
        time1 = time2
        clock.config(text=time2)
        # calls itself every 200 milliseconds
        # to update the time display as needed
        # could use >200 ms, but display gets jerky
    clock.after(200, tick)

tick()

status = Label(root, text="v1.0", bd=1, relief=SUNKEN, anchor=W)
status.pack(in_=statusbar, side=LEFT, fill=BOTH, expand=True)
clock.pack(in_=statusbar, side=RIGHT, fill=Y, expand=False)

root.mainloop(  )


text:
Q: Is there any tool to generate UML diagrams based on a custom grammar? I need a tool/lib to generate UML diagrams from source of a custom programming language grammar. Is there a tool with API or another method to relatively easily tell to generator how it should to interpret the grammar. I have full control of the programming language lexer.
Ask to specific clarification if you have some doubts.

A: Looks like a plain AST visitor should do, shouldn't it? Assuming that you have classes, interfaces, and attributes in your language, that should be easy to handle.
Proper layout of a diagram is a different issue, and can be done afterwards.

A: The reverse engineering of a language into an UML diagram is really a very long and difficult job. If you don't have 12 months research project and deep knowledge of programming and UML then it is better to use an existing tool.


text:
Q: NHibernate Exception: Incorrect syntax near the keyword 'user' I have a table named as User. I declared my class as
    <class name="EETUser"  table="User"> it throws "Incorrect syntax near User keyword".
I then changed to <class name="EETUser"  table="[User]">
This throws the error as Missing table: [User].
I even tried
 <class name="EETUser"  table="'User'">

It throws the same exception.  Table missing.
Please help me out in this.
NB: I cannot change the table name as this table is an existing one for years.

A: You need to declare the schema name in your mapping class tag.
Also, remove the quotes around the table name.
If you cannot change the table name, you can create a synonym and map your entity to the synonym name.
<class name="EETUser"  table="User" schema="**table.schema.name**">


text:
Q: Can't solve because it need *.dll I am new to deploy me first app in Qt and C++.
When I do DoubleClick in me exe of debug folder, I have this message.

But I don't need this .dll to me app. I add this time ago but now I am trying to deploy and find this error.
I review me project.pro and I comment all lines where it is type CGAL.
I detect that it has this problem when I comment one of this lines.
LIBS += -L$$PWD/../../../libs/CGAL/bin
LIBS += -L$$PWD/../../../libs/cgal4.9/auxiliary/gmp/lib

Could anyone tell me, what I need to review more and If I need to check any part of configuration on tools of my Qt program.
Thanks

A: Probably it doesn't find some dll of QT libs's dependencies.
Either you need to deploy your all needed dll into same as your executable output folder:
like such config in .pro config:
 QMAKE_POST_LINK += windeployqt  $$DESTDIR/$${TARGET}.exe $$escape_expand(\n\t)

either you need to configure your windows PATH env variable to add the needed dll path in it.

A: You could use a tool like dependency walker to check why your exe needs the CGAL dll to run.
It can be because of a direct dependency:
app.exe -> CGAL-vc140(...).dll

or an indirect one:
app.exe -> a.dll -> b.dll -> ... -> CGAL-vc140(...).dll

In the first case you should have a line in a .pro a .pri file that looks like this:
LIBS += -lCGAL-vc140(...)

And in the second case:
LIBS += -la

Removing one line or the other and rebuilding (re-run qmake) should remove the dependency.

A: Get DependencyWalker from http://www.dependencywalker.com and open your .exe. It will tell you all the dependencies you miss.
You have to add them to your setup package to deploy your app.


text:
Q: React - import multiple images I'm using react to create an app, and want to import images but i can't just write
I've got an array with every path+filename of images from a repository. The content of the array depends on amount of file in the repo.
I want to create a gallery, with every images from the repository...but as i get path and filenames of images dynamically (when the component is create) i can't just import images in the top of my file like import img1 from "../images/.../image1.jpg"
For the moment i've got the array (called gallerie), and I iterate throught it like that, but images arn't loaded :
{this.state.gallerie.map((image, i) => {
    return ();
})}

How is it possible to display images with their path ? Should I convert them into Base64 ?

A: You could try to use path to change a relative path into absolute, so your app can fetch the image properly.
import * as path from 'path';

{this.state.gallerie.map((image, i) => {
    const path = `${path.resolve(__dirname)}${image}`;

    return ();
})}


text:
Q: Bootstrap Tabs Links Not Working My tabs are not working,every thing is fine .Links are not working properly,,  please help.i try every method but no use.I try CDN , then local  file also
    <!DOCTYPE html>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <meta charset="UTF-8">
        <title>Title</title>

C#

Home

jQuery

PHP

C# IS DEVELOPED BY MICROSOFT CORP IN 2000

This is HOME

A: You need to include the bootstrap js file then also give your menu an id and add a click handler to handle the tab switching, like this:

$('#myTab a').click(function (e) {
  e.preventDefault();
  $(this).tab('show');
});

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>

C#

Home

jQuery

PHP

C# IS DEVELOPED BY MICROSOFT CORP IN 2000

This is HOME

A: You need to include jquery file to run the bootstrap i.e
https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js . You do not need to add any other jquery code.
And also data-toggle will be tab not "tabs".

C#

Home

jQuery

PHP


text:
Q: How to determine number of feature maps in the convolution layer of a CNN? How do we know how many feature maps are needed in the convolution layer?
All steps are clear to me except of this step.

A: I'm no expert, but I believe the idea is that each feature map is being trained to capture a particular aspect of the input.  So the number of feature maps is really a function of how many different features need to be captured and "understood" by the CNN to produce the desired output.
So, I would suggest that if you are classifying many different things (say, 100 different types of pictures) or if what you are classifying has many different subtle aspects to it that could be used to make the classification differentiation then you would want many feature maps.
However, that will slow things down, so if you're only classifying simple things or have only a few classification types then you could get away with fewer feature maps.
Robert


text:
Q: How to join tables without identifiers? For school I have to do this:
Query what salary scale an employee belongs to displaying these columns:
s_schaal.schaal, werknemer.name, werknemer.salaris

But there are no identifiers between the tables. All I have is a bottom line and upper line column (s_schaal.ondergens & s_schaal.bovengrens).
What MySQL query can I use to compare and join this data?

A: I finally figured that joining these tables would not bring a solution. I solved it doing this:
SELECT S.schaal, W.wnr, W.wnaam, W.salaris FROM Werknemer W, S_schaal S
WHERE W.salaris >= S.ondergrens && W.salaris <= S.bovengrens;


text:
Q: I need to convert below function in from DB2 to Oracle, can anybody help? I have no idea about DB2 I need to convert below function from DB2 to Oracle, can anybody help? I have no idea about DB2 :
CREATE FUNCTION READMSGS(   SOURCE_NAME    VARCHAR(12),  SOURCE_SCHEMA  VARCHAR(12), SOURCE_VERSION    VARCHAR(64),  EXPLAIN_LEVEL     CHAR(1))
RETURNS TABLE ( ID varchar(20),
                  DEPTNUM INT,
                  AVGSAL DECIMAL (9,2),
                  EMPCNT INT,
                  WORKDEPT INT )
  LANGUAGE SQL
  DETERMINISTIC
  NO EXTERNAL ACTION
  READS SQL DATA
  RETURN

  SELECT       ID,
               DEPTNUM,
               AVGSAL,
               EMPCNT,
               WORKDEPT
  FROM EMP3  ;

A: All Parameters are unused which bit weird.You need to remove them if they are unused.
It looks simple to me it is simply returning a custom table/type from function. Here is my weak effort to solve your question
1st step would be to create custom type if you don't have any
create or replace type CustomerType(
        ID Varchar2(20),
        DEPTNUM Number,
        AVGSAL Number,
        EMPCNT Number,
        WORKDEPT Number
    );

Secondly modified function in plsql
FUNCTION EXPLAINSMSGS(SOURCE_NAME in VARCHAR2,SOURCE_SCHEMA in VARCHAR2, SOURCE_VERSION in VARCHAR2,EXPLAIN_LEVEL in Varchar2) return record is
  l_customType   CustomerType;
  l_ID Varchar2(20);
  l_DEPTNUM Number;
  l_AVGSAL Nubmer;
  l_EMPCNT Number,
  l_WORKDEPT Varchar2(100);

  Begin
    SELECT     ID,
               DEPTNUM,
               AVGSAL,
               EMPCNT,
               WORKDEPT
    INTO       l_ID,
               l_DEPTNUM,
               l_AVGSAL,
               l_EMPCNT,
               l_WORKDEPT
  FROM EMP3  ;

  l_customType :=CustomerType(l_ID,l_DEPTNUM,l_AVGSAL,l_EMPCNT,l_WORKDEPT);

  Return l_customType;

  End;

A: The DB2 function is declared as DETERMINISTIC. It means it will return the same set of rows for n number of invocation. Glancing through this DB2 code, you will not need a function in Oracle, rather create a view for the select statement as in

  CREATE VIEW explainmsgs AS
      SELECT
            id,
            deptnum,
            avgsal,
            empcnt,
            workdept
      FROM emp3
/


text:
Q: Declaring protected variables in methods I've had a good look round and can't seem to find an answer to this problem.
Basically I'm using the _call method to dynmically generate get and set methods, however when declaring a variable PHP's default is public. Is there anyway to declare a variable from within a class as protected?
function __call($method, $arguments) {
    $prefix = strtolower(substr($method, 0, 3));
    $property = strtolower(substr($method, 3));

    if (empty($prefix) || empty($property)) {
        return;
    }

    if ($prefix == "get" && isset($this->$property)) {
        return $this->$property;
    }

    if ($prefix == "set") {

        $this->$property = $arguments[0];
    }
}

A: One option would be to have a protected array, and to set an element in that array from your magic setter.
class MyClass {
    protected $_myProperties = array();

    public function __get($name) {
        if (isset($this->_myProperties[$name])) {
            return $this->_myProperties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value) {
        $this->_myProperties[$name] = $value;
    }

    public function __isset($name) {
        return isset($this->_myProperties[$name]);
    }
}

A: First off, I'd HIGHLY suggest not returning if the prefix or property variables are not set.  It will make debugging VERY difficult.  Instead, replace the return; with throw new BadMethodCallException('Method Does Not Exist: '.$method);
Second, isn't that defeating the point of protected variables?  It is allowing reading and writing to all properties without any kind of validation.  If you're going to do this, you might as well make them public.
I personally find $foo->bar = 'baz'; to be more readable than $foo->setBar('baz');.  Not because it's "easier" to understand, but because the second is unnecessarally verbose.
Personally, I'd suggest doing a __get and __set, and adding validation.  The whole point of protecting variables is for trust (so that you can trust the settings).  Sure, you could use reflection or sub-classing to change them, but I usually assume that if someone goes that far, they deserve to have any unintended concequnces if they mess up a variable.
And keep in mind that if you are using any kind of magic method, you'll need to add documentation elements if you want your IDE to hint the methods/variables to you...
EDIT:
And don't forget, if you declare __get/__set methods, you can override them in the child classes.  So if the child declares new variables, you can handle them there, and then call parent::__get to handle the default variables.  So don't go with an array just so that you can have one method for all children.  Do the validation for the members you know about, and let your children handle their own validation...

A:
Is there anyway to declare a variable from within a class as protected?

It doesn't seem so.  You can use Reflection to change the accessibility of properties, but it seems that this can only effectively be used to make things public that were not previously public.
You may wish to consider storing automatically generated properties in an an array with the proper visibility.
(There's also __get and __set, but they might not fit your needs.  They'd only get called when a property is missing or inaccessible.  Classes that are able to touch protected properties would bypass them.)


text:
Q: Deref a Arc> to return RwLockReadGuard by default I have the following wrapper for Arc<RwLock<T>>, and I would like to deref them to return the RwLockReadGuard<T> by default.
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
use std::ops::Deref;
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};

#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct ArcRwLock<T: Sized>(Arc<RwLock<T>>);

impl<T> ArcRwLock<T> {
    pub fn new(data: T) -> Self {
        ArcRwLock(Arc::new(RwLock::new(data)))
    }

    pub fn write(&self) -> Result<RwLockWriteGuard<T>> {
        match self.0.try_write() {
            Ok(x) => Ok(x),
            Err(e) => {
                bail!(
                    "RwLock cannot acquire writer lock, error: {}",
                    e.to_string()
                )
            }
        }
    }

    pub fn read(&self) -> RwLockReadGuard<T> {
        self.0.read().unwrap()
    }

}

// impl<T: Sized> Deref for ArcRwLock<T> {
//     type Target = RwLockReadGuard<T>;

//     #[inline]
//     fn deref(&self) -> &Self::Target {
//         self.0.read().unwrap()
//     }
// }

impl<T: PartialEq> PartialEq for ArcRwLock<T> {
    fn eq(&self, other: &Self) -> bool {
        if Arc::ptr_eq(&self.0, &other.0) && ::core::ptr::eq(&*self.0, &*other.0) {
            true
        } else {
            *other.0.read().unwrap().deref() == *self.0.read().unwrap().deref()
        }
    }
}

I wrote the above wrapper mainly for the PartialEq I need for a parent struct to correctly #[derive(PartialEq)].
Most of the time I'm reading the values T from Arc<RwLock<T>>, writing to it is rare.
The above implementation allows me to read/write the values using:
some_arc_object.write()?.uuid = Uuid::new_v4();
let updated_uuid: T = some_arc_object.read().uuid;
// where uuid is a field of T

Since I'm reading the properties most of the time, I'd like to get rid of the repeated .read() and achieve the following by Dereferencing the entire Arc<RwLock>:
let updated_uuid: T = some_arc_object.uuid;
// instead of having to add .read()
// let updated_uuid: T = some_arc_object.read().uuid;

My current humble attempt is shown above in the commented section, trying to make deref() work the same way .read() does. But the compiler is not happy with returning a reference of a local variable. Is there any chance it could be achieved, either by some lifetime magic or other workaround?

A: Dereferences by design should only resolve smart pointers to the pointee, see e.g. the Rust API Guidelines. Acquiring a synchronization guard like MutexGuard or RwLockReadGuard in the Deref definitely goes beyond this guideline and could cause subtle bugs. I.e. you can get implicit locking of a resource without ever explicitly calling lock(), read() or write() on it because it's hidden in the Deref impl which implicitly gets called when resolving a method call.
As for the reasoning why it's not possible: Deref's return type is a reference, thus you need to return something that you can turn into a reference from deref(). The RwLockReadGuard is a value that you're creating inside the deref() scope, thus it's dropped at the end of the scope, which in turn means you're not allowed to hand out a reference to it.
Sometimes it can be ergonomic to wrap whatever you need to do with the value inside the RwLock inside a function, i.e. if it's a String that sometimes gets written to but most of the time you just want to read it, define some convenience method like the following:
struct Foo {
    shared: Arc<RwLock<String>>,
}
impl Foo {
    fn get_shared_str(&self) -> String {
        self.shared.read().unwrap().clone()
    }
}


text:
Q: How do I access sub dictionary values in nested json file? I try to access sub dictionary in nested json file. How do I correctly loop over this data structure? I can access high-level keys without a problem, but I cannot figure out a way to access sub dictionary within one of the keys.
My JSON file looks like this:
with open('all.json') as access_json:
    read_content = json.load(access_json)
read_content.keys()
Out[20]: dict_keys(['documents', 'see', 'rated', 'name', 'points', 'slug', 'logo'])

This I can access without any problems
points_list = read_content['points']
type(points_list)
Out[20]: dict

Then, I can access individual key
points_list['tosdr/review/stackoverflow.com']

Which presents me with
[{'description': 'Generated through the annotate view',
  'discussion': 'https://edit.tosdr.org/points/6166',
  'id': '6166',
  'point': 'bad',
  'privacyRelated': True,
  'score': 70,
  'title': 'This service allows tracking via third-party cookies for purposes including targeted advertising.'},
 {'description': 'Generated through the annotate view',
  'discussion': 'https://edit.tosdr.org/points/6131',
  'id': '6131',
  'point': 'bad',
  'score': 60,
  'title': 'You agree to defend, indemnify, and hold the service harmless in case of a claim related to your use of the service'}]

Now, I can access Interesting values, like this
points_list['tosdr/review/stackoverflow.com'][1]['title']
Out[30]: 'You agree to defend, indemnify, and hold the service harmless in case of a claim related to your use of the service'

What I want to do is extract ALL 'title' from ALL points_list.keys() and create separate json file containing key (['tosdr/review/stackoverflow.com']) + extracted 'title' value. How do I construct such loop?

A: You have to use for-loop to get all titles from dictionary and list
# get elements in dictionary
for key, value in points_list.items():
    # get elements in list
    for item in value:
        print(item['title'])

If you want only from [1]
result = dict()

for key, value in points_list.items():
    result[key] = {'title': value[1]['title']}

or
result = {key:{'title': value[1]['title']} for key, value in points_list.items()}

A: You may try this:
def traverse_dicts( obj ) :
    if isinstance( obj, dict) :
        for k in obj :
            if k == 'title' :
                print 'title:', obj[k]
            else :
                traverse_dicts( obj[k] )
    if isinstance( obj, list) :
        for k in obj :
            traverse_dicts( k )

It will recursively visit all dicts / lists on all levels and print the title contents when found.


text:
Q: What does v=0 in function parameters means Here is a modified code from geeks for geeks.
   #include<iostream>
   using namespace std;

   class Test {
    int value;
   public:
       Test(int v = 0) {value = v;}
    int getValue() {return value;}
   };

   int main() {
       Test t(20);
       cout<<t.getValue();
       return 0;
   }

What does parameter in function Test(int v=0) means?

A: That is default value for v parameter, which is the v variable will use that value if there is no value passed


text:
Q: Calculate quarterly compound interest from yearly simple interest Let's say the yearly simple interest is 10% on a principal of $100. At the end of one year, the new principal is $110. I'm trying to calculate the compound interest equivalent so by the end of the 4th quarter, the new principal should still be $110. In the example below, I'm compounding quarterly (which is incorrect) and I'm ending up with $110.38. How do I modify the formula so I end up at $110?

A: This is technically maths rather than programming but, since Excel is a crossover, we can possibly let it through :-)
The formula for calculating initial capital plus cumulative interest on an amount of b at r% per period over n periods is:

newb = b * (1 + r/100)n

Hence, the formula for getting 10% per year with quarterly interest over that year is (using 1.1, since newb must be 10% higher than b):

1.1 = (1 + r/100)4

So, let's just give the expression 1 + r/100 the term mult for now, and we can work out the rate from that later:
   mult^4 = 1.1
=> mult = ∜(1.1)
=> mult = 1.024113 (roughly)

We can then calculate that the desired interest rate is 2.4113% (by starting with mult, subtracting one, then multiplying by a hundred).
And here's the table to prove it (interest values are rouned):
 Current              New
 Balance  Interest  Balance
 -------  --------  -------
  100.00      2.41   102.41
  102.41      2.47   104.88
  104.88      2.53   107.41
  107.41      2.59   110.00
             -----
             10.00

You can see that you reach the 10% increase at the end of the fourth quarter.

In Excel, assuming A1 holds the desired annual interest rate (like 10) and B1 holds the number of periods in a year (like 4), you can calculate the periodic interest rate with:
= 100 * (power (1 + a1 / 100, 1 / b1) - 1)

as per the following screenshot (which also has the four quarterly calculations):

The formulae for the tabular cells are, if you're interested:
  +  A  +           B           +   C
3 | 100 | =ROUND(a3*$c$1/100,2) | =a3+b3
4 | =c3 | =ROUND(a3*$c$1/100,2) | =a4+b4
5 | =c4 | =ROUND(a3*$c$1/100,2) | =a5+b5
6 | =c5 | =ROUND(a3*$c$1/100,2) | =a6+b6

Feel free to use them as you see fit.

A: With your current setup:
In B5: =B2*(1+B1)^(1/4)
In B6 and drag down: =B5*(1+B$1)^(1/4).


text:
Q: Weird CSS result in Firefox compared to expected result in chrome (some divs are not aligned but shifted down) With this HTML markup :

short tag

1154353

A quite long long long long long tag

5

And this CSS rules :
.tag-list {
    border:1px solid red;
}

.tag {
    border:1px solid green;
    display:inline-block;/*so that tags are lined up like words... */
    margin-right: 0.5em;
    margin-bottom: 0.5em;
    white-space:nowrap; /* so that label & tail sub-divs are stuck all together */
    height: 2em;
    line-height: 2em; /* text is vertically centered */
}

.tag > div {
    height: 100%;
    display:inline-block; /*so that label&tail are lined up */
}

.tag-tail {
    border:1px solid orange;
}

.tag-label {
    border:1px solid blue;
    overflow:hidden;
    text-overflow:ellipsis;
    max-width:10em; /* to generate a (text) overflow for the ellipsis*/
}

I get the expected result in Chrome 22.0.1229.94
But in Firefox 15.0.1, i get a weird result (div.tag-tail elements are shifted down) !
You can compare the results in FF and Chrome with this jsFiddle.
I know that adding the property overflow:hidden; to the selector/rule .tag-tail fixes the issue, but i'd like to understand why this is needed for FF and why there is this difference in behaviors ?
Thank you for your answers !

A: The CSS spec says at http://www.w3.org/TR/CSS21/visudet.html#leading last paragraph:

The baseline of an 'inline-block' is the baseline of its last line box in the normal flow, unless it has either no in-flow line boxes or if its 'overflow' property has a computed value other than 'visible', in which case the baseline is the bottom margin edge.

So in your case, the .tag-label has its baseline at the bottom of its margin edge (and since it has no margins, that means at the bottom edge of its bottom border.  But the .tag-tail has its baseline on the baseline of the text inside it.  And since everything here is baseline-aligned, that means that the baseline of the text in the .tag-tail needs to end up on the same vertical position as the bottom of the border for the .tag-label.
Which is exactly what Firefox does.  Chrome doesn't implement the spec for baselines of inline blocks correctly; see https://bugs.webkit.org/show_bug.cgi?id=36084

A: Adding overflow:hidden; seems like a strange thing to add.
I would do what loic suggested in the comments:
Add vertical align.
I was going through a similar issue earlier, vertical-align:top; was my solution as well.
(By the way, Firefox 16 will also display undesirable results.)
.tag > div {
     height: 100%;
    display:inline-block;
    vertical-align:top;
    }

A: You just had too much stuff going on in .tag-label
Here is your solution:
http://jsfiddle.net/mrbinky3000/JU5Cr/
.tag-label {
    border:1px solid blue;
}

But this is a better solution:
http://jsfiddle.net/mrbinky3000/gwb7d/1/
.tag-list {
    border: 1px solid red;
    display: block;
}

.tag {
    border:1px solid green;
    display:inline-block;/*so that tags are lined up like words... */
    margin-right: 0.5em;
    margin-bottom: 0.5em;
    white-space:nowrap; /* so that label & tail sub-divs are stuck all together */
    height: 2em;
    line-height: 2em; /* text is vertically centered */
    overflow: hidden;

}

.tag > div {
    height: 100%;
    display:block;
    float: left;
}

.tag-tail {
    border:1px solid orange;
}

.tag-label {
    border:1px solid blue;
}

If you float a div, it comes out of the "page flow" and the div shrinks to fit the contents, very similarly to what happens when you set something to "inline-block".  However, unlike inline-block, you don't have to worry about whitespace in the code messing things up.   Display block ignores leading and trailing whitespace.


text:
Q: CQ5.5 get .infinity.json of a resource in a servlet If we had component resource set up as such:

*

*mycomponent

*

*mycomponent.jsp

*mycomponent.JSON.jsp

We can Assume it will work as such:

*

*/path/to/mycomponent.html => see html

*/path/to/mycomponent.json => see my json

Also in a servlet we might be able to do something like
Resource myResource = resourceResolver.getResource(request, "path/to/mycomponent");

I'm just curious how I might be able to get the .json representation in a servlet context as well.
I've done something that sort of solves this, but I was wondering if there was an alternate way, as this solution has huge limitations. Basically I load the Node at the path and do JSONDumps of the Node and it's children. This would allow me to get a larger set of JSON from the resource at the mycomponent.getPath(), but it doesn't allow me the ability to pull the custom JSON view i've created via mycomponent.JSON.jsp.
any thoughts/advice would be great, thank you.

A: To capture the output of rendering a resource you can use the SlingRequestProcessor service, which makes a request internally without going through the network layers but still using all the same rendering mechanisms that are used to process HTTP requests.
If you just need to include such output in the rendering that you are computing you can use Request.getRequestDispatcher(somePathWithJsonExtension).include(request, response) which is what the Sling and CQ include JSP tags do.
Using resourceResolver.getResource(...) does not do any rendering, it just provides a raw Resource which is a data/content object.

A: The title of the question sounds like you want wanted to get the equivalent of a cURL/AJAX call to /path/to/mycomponent.-1.json but within a Servlet or other Java class.
You can use the org.apache.sling.commons.json.jcr.JsonItemWriter class to dump a JCR node into a JSONObject with infinite recursion. By passing in a Set into the constructor you can specify which properties to exclude from the final JSON. See http://www.nateyolles.com/blog/2015/12/converting-aem-sling-resources-to-json for more examples.
Resource resource = resolver.getResource("/content/my-app/my-page");

if (resource != null) {
    Node node = resource.adaptTo(Node.class);
    StringWriter stringWriter = new StringWriter();
    JsonItemWriter jsonWriter = new JsonItemWriter(null);

    try {
        jsonWriter.dump(node, stringWriter, -1);
        JSONObject jsonObject = new JSONObject(stringWriter.toString());
    } catch (RepositoryException | JSONException e) {
        LOGGER.error("Could not create JSON", e);
    }
}

You can also use the org.apache.sling.engine.SlingRequestProcessor class as Bertrand discussed above. See http://www.nateyolles.com/blog/2015/10/get-rendered-html-for-an-aem-resource-or-component for more examples.
@Reference
private RequestResponseFactory requestResponseFactory;

@Reference
private SlingRequestProcessor requestProcessor;

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    /* Setup request */
    HttpServletRequest req = requestResponseFactory.createRequest("GET",
            "/content/my-app/my-page.-1.json");

    /* Setup response */
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    HttpServletResponse resp = requestResponseFactory.createResponse(out);

    /* Process request through Sling */
    requestProcessor.processRequest(req, resp, request.getResourceResolver());
    String jsonString = out.toString();
}

A: Remember that you are using a JSP page to render out your JSON. If you are using a sling servlet to do this, there are several approaches that are feasible, but it's not the best approach to do so trying to write out responses directly yourself, especially since you have a JSP view to do that for you.
Have a look at this post:
servlet result display in jsp page
Specifically:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    Object data = "Some data, can be a String or a Javabean";
    request.setAttribute("data", data);
    request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}

If you just want to render out some JSON.
Otherwise, another less elegant option is to make a synchronous local HTTP request to the JSON.
Hope that helps.


text:
Q: Nested fractional denominator(up to infinity)calculation Question:
$$4 + \dfrac{1}{2 + \dfrac{1}{1 + \dfrac{1}{3 + \dfrac{1}{1+\dfrac{1}{2 + \dfrac{1}{8 + \dfrac{1}{\ddots}}}}}}} = \sqrt{A}$$
Find the positive integer $A$ in the equation above.
Details and assumptions

*

*The pattern repeats 2, 1, 3, 1, 2, 8 infinitely, but 4 comes only once, i.e., at the beginning.

My Approach:
I was thinking whether I should calculate each fractional part of the denominators or is there any other shorter method to solve this problem.

A: Let's take a simpler example first: say, $$\sqrt{A}=1+{2\over 3+{2\over 3+...}}.$$ Here the repetition $2,3,2,3, ...$ continues forever after the $1$.
The problem is that this looks on the face of it like some sort of "infinitary" equation (or rather, it's a normal equation with an "infinitary" term in it). We want to somehow "tame" the right-hand side.
This is where the repetition, or self-similarity, comes in. Let $x={2\over 3+{2\over 3+...}}$. Then if we take the reciprocal of both sides, we see something interesting: $${1\over x}={3+x\over 2}.$$ Solving for $x$ yields $$x^2+3x-2=0,$$ which has as its solutions $$-3\pm\sqrt{9+8}\over 2,$$ that is, $$x={\sqrt{17}-3\over 2}\quad\mbox{or}\quad x={-\sqrt{17}-3\over 2}.$$ Since $x$ is clearly positive$^*$, it has to be the former.
Plugging back into the original expression, we have $$\sqrt{A}=1+x={\sqrt{17}-1\over 2}.$$ Squaring both sides finishes the problem.
Can you see how to follow a similar argument here? (It's definitely going to be messier since your patter takes longer to repeat, but the basic idea still applies.)
An interesting feature of this argument is: it totally breaks down if we don't have repetition! To see what I mean, try to calculate $$1\over 2+{3\over 4+{5\over 6+...}}.$$ In general, things are much more complicated and the "naive" argument above simply doesn't work.

There is a subtlety here; namely, that we haven't really defined what an "infinitary" fraction (called a "continued fraction") like this actually is. But it should be clear that any reasonable definition will yield a positive answer here, since no piece involved is negative.


text:
Q: How can I shift an array further left? I want to move an array about 3 or 4 cm further to the left. Knowing how to align it on the left side of the page could be useful too.
The code is:
\documentclass{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\begin{document}
    \section*{Question 10}
    \begin{figure}[h!]
        \includegraphics[width=\linewidth]{"D:/.../question 10".png}
    \end{figure}
    Let $K\hat{P}L = x$ and $K\hat{Q}M = y$. Required to prove: $\triangle KPL ||| \triangle KMQ$.
    \linebreak
    \[ \begin{array}{rll}
        & O\hat{M}Q=y & (\text{isoc.} \triangle, OQ=OM)\\
        \Rightarrow \ & P\hat{O}M = 2y & (\text{ext.} \angle \triangle)\\
        \Rightarrow \ & \text{reflex} \angle P\hat{O}M =360^{\circ}-2y & (\angle \text{'s around a point})\\
        \Rightarrow \ & 2P\hat{L}M = 360^{\circ}-2y & (\angle \text{at cntr}= \times 2)\\
        \Rightarrow \ & P\hat{L}M = 180^{\circ}-y\\
        \Rightarrow \ & K\hat{L}P = y & (\angle \text{'s on st. line})\\
    \end{array} \]
    So, in $\triangle KPL$ and $\triangle KMQ$
    \[ \begin{array}{rll}
        1. & \hat{K} \text{ is common}\\
        2. & K\hat{L}P=y=K\hat{Q}M\\
        \vspace{4mm}
        \therefore & \triangle KPL ||| \triangle KMQ & (A.A.)
    \end{array} \]
\end{document}

I want to align the second array further left.
The document looks like this:

Secondly, it seems as if the \vspace{2mm} command is not working. How can I get a bit more space in-between the last two lines?
Thirdly, why is the word "Let" and the word "So" not aligned?

A: You can use the missile flalign* to left align the equations.
\begin{flalign*}
& equation &
\end{flalign*}

You can align the parts using the & method of flalign* itself, but I left it as an exercise.
You can add the vertical space using \\[4mm]
Let is indented so not aligned with So. Use \noindent.
Code:
\documentclass{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\begin{document}
    \section*{Question 10}
    \begin{figure}[h!]
        \includegraphics[width=0.2\linewidth]{example-image}
    \end{figure}
    \noindent Let $K\hat{P}L = x$ and $K\hat{Q}M = y$. Required to prove: $\triangle KPL ||| \triangle KMQ$.
    \begin{flalign*}
    &\begin{array}{rll}
        & O\hat{M}Q=y & (\text{isoc.} \triangle, OQ=OM)\\
        \Rightarrow \ & P\hat{O}M = 2y & (\text{ext.} \angle \triangle)\\
        \Rightarrow \ & \text{reflex} \angle P\hat{O}M =360^{\circ}-2y & (\angle \text{'s around a point})\\
        \Rightarrow \ & 2P\hat{L}M = 360^{\circ}-2y & (\angle \text{at cntr}= \times 2)\\
        \Rightarrow \ & P\hat{L}M = 180^{\circ}-y\\
        \Rightarrow \ & K\hat{L}P = y & (\angle \text{'s on st. line})\\
    \end{array} &
    \end{flalign*}
    So, in $\triangle KPL$ and $\triangle KMQ$
    \begin{flalign*}
     &\begin{array}{rll}
        1. & \hat{K} \text{ is common}\\
        2. & K\hat{L}P=y=K\hat{Q}M\\[4mm]
        \therefore & \triangle KPL ||| \triangle KMQ & (A.A.)
    \end{array} &
    \end{flalign*}
\end{document}


text:
Q: VB no install of .net I have a vb app working now but many users have complained to me that it requires .net library installed. Is there a way to bundle it with my program without having a seperate exe?

A: If you use the packaging tool which comes with the VB6 IDE (can you really call it that?), it will install all the dependencies with the app.  However, I'm not sure that's the real problem here because VB6 doesn't depend on the .NET framework.

A: I'm assuming that you're using VB.NET (rather than just VB, as your tags suggest). In this case, no, there is no possible way to eliminate needing the .NET framework. While you can list it as a prerequisite and include it with your setup project, you cannot eliminate the dependence upon it.

A: Take a look at VMWare ThinApp http://en.wikipedia.org/wiki/VMware_ThinApp.  It's a commercial appplication, but it's the only thing I know of that might do what you want.

A: I had this problem earlier, solution is
Pack all necessary .net frameworks [2.0,3.0,3.5,4.0,4.5,later], in installer exe,  then program installer, to run installation of all .net frameworks.
Suggestion: each .net framework installer has switches, study and apply proper switch [like /s , /i]. This installers have un-attend installation switch too.
Then send new installer to all users and will be happy with the improvements.
Regards.

A: I've found that the biggest complaint with users (and biggest source of installation confusion) is having to install a separate runtime for .NET, along with the application. Especially if they have to go through 2 hours of Windows Update downloads and reboots to obtain it! Creating a setup package that includes the .NET runtime and installs this seamlessly, along with your application, should make things go much smoother for your users. Most people expect to have to install applications first before they use them anyway.
Creating a simple setup application is easy in Visual Studio. See Microsoft's guide here: http://msdn.microsoft.com/en-us/library/k3bb4tfd.aspx
There are other third-party installer programs you can use, but I'll mention here that my favorite is definitely Inno Setup, which I highly recommend. The website is here: https://jrsoftware.org/isinfo.php. You can write a simple script that will automatically install the current version of the .NET framework, if the user doesn't already have it installed.

A: If you're using VB.NET, then it's not possible, VB.NET is too reliant on .NET framework for everything.
However, you might want to backport your code into VB6, which does not require .NET framework.


text:
Q: wpa_supplicant connects with static IP but not dhcp Currently working on an OpenEmbedded/Yocto board, and I'm running into an issue with Wifi.
Inside of interfaces, if I set a static IP, and assign it my network, gateway, netmask, and dns, it works when connecting to a specific wireless access point with wlan0.
However, if I set wlan0 to inet dhcp, instead of inet static, then it can connect to the access point, ping other things on the network, but it cannot get out to the internet. I have tried many things to get it to work, but to no avail.
I have played with wpa_supplicant, and interfaces, as well as udhcpc in order to try and get this to work, but nothing is working.
Does anyone have any ideas?
Edit 1: Took a look at route -n with both dhcp and static. The only difference is that with dhcp, Metric is set to 10 on the dhcp attempt, and 0 on the static.


text:
Q: An equivalence relation iff G≈H, where G and H are groups
Problem : Let $S$ be the relation G~H iff G is isomorphic to H.

Show reflexive, transitivity and symmetric.
First show G is automorphism, which will imply G~G. So the identity mapping gives us this automorphism.  So G~G. My question is, is this the right process for showing reflexiveness?
Now we show symmetry. Assume G is isomorphic to H. Thus there exists a mapping $\phi:G ->H$.  We must show H is isomorphic to G. Since $\phi$ is this mapping, consider $\phi^{-1}.$ This is a bijection since $\phi$ is a bijection. How do I show it is homomorphic?
Finally show its transitive. This I have done in a previous problem.
This is different than the duplicate as suggested because previously I had done it incorrectly. I know now I must do it this way.

A: If $\phi$ is an isomorphism, we have $\phi(a)\phi(b)=\phi(ab)$. Therefore, taking $a=\phi^{-1}(u)$ and $b=\phi^{-1}(v)$ for any $u$ and $v$, we deduce that $uv=\phi(\phi^{-1}(u)\phi^{-1}(v))$, or $\phi^{-1}(uv)=\phi^{-1}(u)\phi^{-1}(v)$. In other words, $\phi^{-1}$ is an isomorhism.


text:
Q: Bubble sort con whiles Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
public static ArrayList<Integer> BubbleSort(ArrayList<Integer> data) {
    ArrayList<Integer> result = data; //Resultado
    boolean swaped = false; //Variable en caso de que no haya intercambio
    int i = 0;
    int j = 0;

    while (i < result.size() - 1) {
        swaped = false;
        i++;

        while (j < result.size() - i - 1) {

            //obtenemos los valores
            Integer pos = result.get(j);
            Integer next = result.get(j + 1);

            //si la pos es mayor que el siguiente intercambia
            if (pos > next) {
                result.set(j, next);
                result.set(j + 1, pos);
                swaped = true;
            }

            System.out.println(result);
            j++;
        }

        if (!swaped) {//si no hubo intercambio se acaba el método
            break;
        }
    }
    return data;
}

Results:
Before :
[13, 7, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 18, 5, 2]
[7, 13, 5, 18, 2]

After :
[7, 13, 5, 18, 2]

BUILD SUCCESSFUL (total time: 0 seconds)

Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
Estoy tratando de hacer un bubble sort con array list, usando solo while. Pero no me esta saliendo.
Este el codigo corregido, pero sigue saliendo los mismo resutados.
 public static ArrayList<Integer> BubbleSort(ArrayList<Integer> data) {

    ArrayList<Integer> result = data; //Resultado

    boolean swaped = true; //Variable en caso de que no haya intercambio
    int i = 0;
    int j = 0;

    while (swaped) {

        swaped = false;
        i++;

        while (j < result.size() - i - 1) {

            //obtenemos los valores
            Integer pos = result.get(j);

            Integer next = result.get(j + 1);

            //si la pos es mayor que el siguiente intercambia
            if (pos > next) {

                result.set(j, next);

                result.set(j + 1, pos);

               // swaped = true;
            }

            System.out.println(result);
            j++;

        }

    }
    return result;

}

Before :
[13, 7, 18, 5, 2]
  [7, 13, 18, 5, 2]
  [7, 13, 18, 5, 2]
  [7, 13, 5, 18, 2]
After :
[7, 13, 5, 18, 2]
BUILD SUCCESSFUL (total time: 0 seconds)

A: Lo que esta mal, no es tu código, es tu algoritmo.
El método burbuja sigue ejecutándose hasta que no haya mas cambios. La cantidad de veces que se ejecuta, es indefinida.
boolean swaped = false; //Variable en caso de que no haya intercambio

Esta variable es correcta, y tu while debe seguir siempre que esta variable sea true. mejor, seteala como true ;)
while (i < result.size() - 1) {

Esta linea no tiene ningún sentido. Ahí lo que tenes que controlar es si hubo cambios o no, tu while debería ser
while (swapped) {
    swaped = false;

Recuerda poner swapped a true antes de entrar. Y setearlo a false exactamente después de entrar, como haces ahora.
Y esto:
if (!swaped) {//si no hubo intercambio se acaba el método
    break;
}

No tiene ningún sentido. Hace esos cambios, y vas a ver como va a funcionar ;)


text:
Q: php, sessions, arrays - how to assign strign to the end of the session array I have this small code , why it does not work and how to make it correctly ?
$temp = $_SESSION['contactPersonInterest'][$i];
$temp += ',Medlemskort';
//$_SESSION['contactPersonInterest'][$i] = $temp;

I am testing it with
?><script>alert('<?php echo  $_SESSION['contactPersonInterest'][$i] ?>'+'----------'+'<?php echo $temp ?>');</script> <?php

And what i get is :
blbla,blll----------0

Whats wrong ?
Thank you

A: String concatenation is done with . in PHP. Try:
$temp .= ',Medlemskort';

Otherwise you perform addition, and if both strings don't start with numbers, they will be converted to 0 and 0 + 0 = 0 :)
Have a look at Type Juggling.

A: That's because += is an operator for adding integers, not strings. You want to concatenate strings (which is "."). Also, there is no need to create a temporary variable, only to overwrite the existing one. This should work:
$_SESSION['contactPersonInterest'][$i] .= ',Medlemskort';

A: You wrongly assign more things to the variable via +. You should use . instead.
$temp .= ',Medlemskort';

A: If you want $i to have temp's value, no need for the +=:
$temp = ""; // good habit to initialize before usage
$temp = $_SESSION['contactPersonInterest'][$i];
$temp = ',Medlemskort';
$_SESSION['contactPersonInterest'][$i] = $temp;
// or even save a $temp
 $_SESSION['contactPersonInterest'][$i] = ',Medlemskort';

Hope this makes sense, good-luck


text:
Q: Unable to run LSTM model on python 3.7, Tensorflow 1.15.0 I'm new to LSTM modelling, and try some basic coding. I'm getting error while adding and when fitting the model
The link i'm referring https://analyticsindiamag.com/how-to-code-your-first-lstm-network-in-keras/
Please help me as where i'm going wrong and how to fix it
Python Version is 3.7
Tensorflow Version 1.15.0
Code
    import keras
        from keras.datasets import mnist
        from keras.models import Sequential
        from keras.layers import CuDNNLSTM, Dense, Dropout, LSTM
        from keras.optimizers import Adam

#Importing the data
        (X_train, y_train),(X_test, y_test) = mnist.load_data()  # unpacks images to x_train/x_test and
labels to y_train/y_test
#Normalizing the data
         X_train = X_train.astype('float32') / 255.0
         X_test = X_test.astype('float32') / 255.0

#Initializing the classifier Network
         classifier = Sequential()

#Adding the input LSTM network layer
         classifier.add(CuDNNLSTM(128, input_shape=(X_train.shape[1:]), return_sequences=True))
         classifier.add(Dropout(0.2))

#Adding a second LSTM network layer
         classifier.add(CuDNNLSTM(128))

#Adding a dense hidden layer
         classifier.add(Dense(64, activation='relu'))
         classifier.add(Dropout(0.2))

#Adding the output layer
         classifier.add(Dense(10, activation='softmax'))

         classifier.add(LSTM(128, input_shape=(X_train.shape[1:]), return_sequences=True))

#Compiling the network
          classifier.compile( loss='sparse_categorical_crossentropy',
              optimizer=Adam(lr=0.001, decay=1e-6),
              metrics=['accuracy'] )

#Fitting the data to the model
           classifier.fit(X_train,y_train,epochs=3,validation_data=(X_test, y_test))

Getting error while running below code
Error 1:
  classifier.add(LSTM(128, input_shape=(X_train.shape[1:]), return_sequences=True))

  ValueError: Input 0 is incompatible with layer lstm_19: expected ndim=3, found ndim=2

Error 2:
  classifier.fit(X_train,y_train,epochs=3,validation_data=(X_test, y_test))

  AttributeError: 'Sequential' object has no attribute '_feed_output_names'


text:
Q: Why won't my video play any sound on Safari even though I didn't touch that configuration at all? I just don't understand how my video just doesn't want to play any sound on Safari mobile browser.  I've tried a laundry list of things I found on the web and on SO but to no avail.
What can I do to fix this?  Code's below.
<video width="100%" id="vid-player" class="vid img-responsive" style="max-width: 100%;" autoplay playsinline><source src="${this.fill}" type="video/mp4">Your browser does not support the video tag</video>`

A: In April of 2018, Google updated Chrome such that videos no longer autoplay without users' consent. Source: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes


text:
Q: Printing nodes field value I would like to print nodes field value in Drupal 7 PHP block but when i'm using the code:
<?php
if (arg(0) == 'node' && is_numeric(arg(1))) {
  if ($node = node_load(arg(1))) {
    if ($node->type == 'offer') {
      $company_name = check_plain($node->field_company[0]['value']);
    }
  }
  if (!empty($company_name)) {
    print $company_name;
  }
}
?>

it does nothing - nothing prints. I'm sure that my variable is empty, but why? What am I doing wrong?
Thanks for any help

A: $company_name = check_plain($node->field_company[0]['value']);

That's sooo D6. :) In D7, by default it would be:
$company_name = check_plain($node->field_company[$node->language][0]['value']);

Generally, just print_r/var_dump (or kpr/dpr if you have devel installed) $node object there to see what fields you have inside and how to access them.


text:
Q: Fresh Install of Ubuntu 14.04 LTS (No Dual Boot) - Getting No Bootable Device Really hoping some one can assist as I'm concerned that I have done something wrong with my new installation of Ubuntu 14.04 LTS, with no dual boot on my Acer Aspire ES1-512-C32A.
Basically, when I remove my Live USB Flash drive and reboot, press F2 for BIOS, I change boot order to used my HDD, see nothing that mentions Ubuntu Boot or anything relating to Ubuntu, so just choose my HDD name - save changes, machine reboots and straight off, just get the message "No Bootable Device"
Have tried to search other similar threads but am not understanding exactly what I need to do.
I see something like using efibootmgr, which I assume has to performed from Live USB bootup but receive the message: command not found.
Really keen to get this working on my Acer Aspire but would really appreciate the required steps to fix this issue, which again, I assume will be from my bootable Ubuntu flash drive.
Simple steps would really be great.
Thanks.

A: Try running boot repair as a first step.  Google for the official boot repair ubuntu page.  Sorry I can't post a fancier answer, I am on a phone.


text:
Q: File not uploading to directory - even when www-data has group permission in the upload folder I have got this to work with 777 file permission: but cannot understand why more restrictive file permissions will not work.
Linux Groups:

*

*alex

*www-data

Linux Users:

*

*alex (belongs to www-data and alex)

*www-data (belongs to www-data and alex)

Directory Structure
uploads (directory,owner=alex,group=alex,chmod=660)
Problem
A PHP/Wordpress Admin form (on apache) is used to upload a file to this directory.  If the folder permissions are anything below 777, even 766, the file will not upload, and I cannot understand why.


text:
Q: how to bind a bind_param with non variables i have a funktion that is suposed to make it easy to make prepared sql querys
here is the function
    function preparedConnection($stmt,$param){
    $dbUsername= 'root';
    $dbPassword='';
    $dbip = 'localhost';
    $db = '129393';

    $conn = new mysqli($dbip, $dbUsername, $dbPassword, $db);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    echo $stmt."<br>";
    $stmt_db = $conn->prepare($stmt);
    echo $param;
    $stmt_db->bind_param($param);

    $stmt_db->execute();
    $stmt_db->close();
    $conn->close();
    exit();
}

here is how i use it
       $stmt = "INSERT INTO task_times (task_id, login_id, title, description,
    used_fixed_price_per_hour ,used_discount_percent, used_price_type) VALUES (?, ?, ?, ?, ?, ?, ?)";

    $param = "'iissiii', $task_id , $login_id, '$title', '$description', $used_fixed_price_per_hour, $used_discount_percent, $used_price_type";

    $db->preparedConnection($stmt,$param);

but i does not accept vaiables that are string eny help?

A: You need to pass each parameter to bind_param() individually.
A possible solution that gives you a bit more flexibility than hardcoding it, would be to use array unpacking: You pass an array with all individual values and unpack it where you need it:
$param = [
    'iissiii',
    $task_id,
    $login_id,
    // etc.
];

And in your function:
$stmt_db->bind_param(...$param);