text:
Q: How to disable swagger 3 configuration in spring boot I have a requirement to support swagger 2 & 3 in my spring boot API.
I have created swagger 2 using docket object & for swagger 3 just added maven dependency springdoc-openapi-ui. Able to check swagger 2 & 3 documentation.
how do I disable/enable only swagger 3 or swagger 2? I mean how do I disable swagger 3 configurations?
I don't have swagger 3 configuration class to enable/disable by using @profile. Just adding springdoc-openapi-ui maven dependency swagger 3 worked.

A: Here's the answer copied from this comment

The following property is available since: v1.1.16
springdoc.api-docs.enabled=false This property helps you disable
springdoc-openapi endpoints.
If you want to expose the api-docs endpoints without using the
swagger-ui, you can use the core dependency:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-core</artifactId>
    <version>1.1.16</version>
</dependency>


text:
Q: SVG source not correct I have a brand new create react app with typescript and storybook. When I try to get a svg source code I get something like this "e4392967a87a6d4ec600.svg" and not the source. Am I missing a loader or something.
My code is like this:
  import(`/svg-embed/basket.svg`).then((content) => {
    console.log("content: ", content);
    return(setSvgContent(content.default));
  });

My content.default is just e4392967a87a6d4ec600.svg

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure AD B2C, ASP.NET Mvc and JQuery Ajax - Refreshing expired token via Ajax problem I have a web application that is built using .NET 7.0 and Mvc/Razor.  This application is secured by Microsoft Identity libraries and Azure AD B2C.  I have added the [Authorize] attribute to the Mvc controllers and this is working perfectly.  I can log in and the pages can access the controllers correctly, and if the auth tokens expire, they are refreshed correctly, etc.
The problem comes when I try to access some of the endpoints in the mvc controllers via a JQuery Ajax call in a page.  When I make a call, and the auth tokens have expired, I see a 302 response (which is correct behaviour I believe) but then I get a CORS error.  But more specifically, the error that appears in the Chrome DevTools console is:
Access to XMLHttpRequest at 'https://xxxxx.b2clogin.com/xxxxx.onmicrosoft.com/b2c_1a_signup_signin/oauth2/v2.0/authorize?<additional stuff>' (redirected from 'http://localhost:57152/<mvc controller endpoint>?callback=jQuery360002914740315700981_1669878277934&_=1669878277935') from origin 'http://localhost:57152' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I believe the way to handle this is to intercept the 302 response, change it to a 401 (unauthorized) response and then have AJAX handle the 401 by taking the user a login page.  Is this the correct approach?  If so, how do I go about intercepting the 302 response?  Because I tried to do this with a custom Authorize attribute on the controller, but the CORS error happened before the attribute could have a chance to intercept.
I've spent many hours looking for a solution to this so hopefully someone has experienced this same issue and has managed to solve it.

A: I ended up solving this issue by doing two things ... adding some middleware to startup.cs and handling the JQuery method .ajaxError.
The middleware, which intercepts a request to work out if it has a 302 response (typical when a auth token is being refreshed) and the request is a AJAX request.  If so, change the response to a 401 unathorized.
app.Use(async (context, next) =>
{
    await next.Invoke();

    // Is the response a redirect?
    if (context.Response.StatusCode == StatusCodes.Status302Found)
    {
        // Is the request an AJAX request?
        if (context.Request.Headers.TryGetValue("X-Requested-With", out var headerValue) && headerValue == "XMLHttpRequest")
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        }
    }
});

The JQuery AJAX error method checks to see if the error is a 401 error.  If so, then send the browser to the Sign In page, which will either automatically refresh the auth token, or prompt the user to sign in again.  In my example, below, I'm using a DevExpress control to let the user know the session has expired.
$(document).ajaxError(function(event, request, settings) {
    if (request.status === 401) {
        var result = DevExpress.ui.dialog.alert("
Your session has expired and we will attempt to log you in again.

Please note, this will refresh the page and you will lose unsaved data.
", "Session Expired");
        result.done(function () {
            var signInUri = '@(Url.Content("~/MicrosoftIdentity/Account/SignIn?redirectUri="))' + encodeURIComponent(location.pathname);
            location.href = signInUri;
        });
    }
});

This is working for me, but I'm open to solutions that handle this scenario in a more robust, elegant fashion.


text:
Q: SQL Server query for multiple conditions on the same column Here's the schema and data that i am working with
CREATE TABLE tbl (
    name varchar(20) not null,
    groups int NOT NULL
);

insert into tbl values('a', 35);
insert into tbl values('a', 36);
insert into tbl values('b', 35);
insert into tbl values('c', 36);
insert into tbl values('d', 37);

| name | groups|
|------|-------|
| a    | 35    |
| a    | 36    |
| b    | 35    |
| c    | 36    |
| d    | 37    |

now i need names of only those that are having group greater than or equal to 35
but also an additional is that i can only include a row for which group=35 when a corresponding groups=36 is also present
| name | groups|
|------|-------|
| a    | 35    |
| a    | 36    |

second condition is that it CAN include those names that are having groups greater than or equal to 36 without having a groups=35
| name | groups|
|------|-------|
| c    | 36    |
| d    | 37    |

the only case it should leave out is where a record has only groups=35 present without a corresponding groups=36
| name | groups|
|------|-------|
| b    | 35    |

i have tried the following
select name from tbl
where groups>=35
group by name
having count(distinct(groups))>=2
or groups>=36;

this is the error i am facing Column 'tbl.groups' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

A: So, as far as i can tell you just want to limit where groups 35 is by itself. I thought, lets try and isolate those names where they only have groups=35 and then not exists from there. Is this the correct output youre after?
Also, using complicated OR's in the where clause will often lead to your query not being SARGable. Better to UNION or some how building the query so that each part can use indexes (if they can).
if object_id('tempdb..#tbl') is not null drop table #tbl;
CREATE TABLE #tbl (
    name varchar(20) not null,
    groups int NOT NULL
);

insert into #tbl values('a', 35), ('a', 36), ('b', 35), ('c', 36), ('d', 37);

select *
from #tbl tbl
WHERE NOT EXISTS
    (
        SELECT COUNT(groups), name
        FROM #tbl t
        WHERE EXISTS
            (
                SELECT name
                FROM #tbl tb
                WHERE groups = 35
                and tb.name=t.name
            )
        AND t.name = tbl.name
        GROUP BY name
        HAVING COUNT(groups)=1
    )
;

A: It looks like you need an exists() condition. Try:
select *
from tbl t
where t.groups >= 35
and (
    t.groups > 35
    or exists(select * from tbl t2 where t2.name = t.name and t2.groups = 36)
)

There are other ways to arrange the where clause to achieve the same effect. Having the t.groups >= 35 condition up front should give the query optimizer the ability to leverage an index on groups.

A: You can use a windowed count for this
This avoids joining the table multiple times
SELECT
  name,
  groups
FROM (
    SELECT *,
      Count36 = COUNT(CASE WHEN groups = 36 THEN 1 END) OVER (PARTITION BY name)
    FROM tbl
    WHERE groups >= 35
) tbl
WHERE groups >= 36 OR Count36 > 0;

db<>fiddle

A: Try this:
DECLARE @tbl table ( [name] varchar(20) not null, groups int NOT NULL );

INSERT INTO @tbl VALUES
    ('a', 35), ('a', 36), ('b', 35), ('c', 36), ('d', 37);

DECLARE @group int = 35;

; WITH cte AS (
    SELECT
        [name]
        , COUNT ( DISTINCT groups ) AS distinct_group_count
    FROM @tbl
    WHERE
        groups >= @group
    GROUP BY
        [name]
)
SELECT t.* FROM @tbl AS t
INNER JOIN cte
    ON t.[name] = cte.[name]
WHERE
    cte.distinct_group_count > 1
    OR t.groups > @group;

RETURNS
+------+--------+
| name | groups |
+------+--------+
| a    |     35 |
| a    |     36 |
| c    |     36 |
| d    |     37 |
+------+--------+

Basically, this restricts the name results to groups with a value >= 35 with more than one distinct group associated, or any name with a group value greater than 35. Several assumptions were made in regard to your data, but I believe the logic still applies.


text:
Q: Auto Adjust height of multiline editor for in MVC using bootstrap I have below editorfor which is multiline, I need to auto adjust height when user starts adding multiple email address in separate lines using bootstrap. Any code example is highly appreciated.
Model:
     [DataType(DataType.MultilineText)]
     public string AdditionalEmailAddressesText { get; set; }

View:

        @Html.LabelFor(m => m.AdditionalEmailAddressesText, new { @class = "col-sm-2 control-label" })

            @Html.EditorFor(m => m.AdditionalEmailAddressesText, new { htmlAttributes = new { @class = "form-control", placeholder = @Strings.Porting_AdditionalEmailAddressesSubtext } })
            @Html.ValidationMessageFor(m => m.AdditionalEmailAddressesText)

A: For textarea tag, there's no auto-height attribute to make it adjust the height automatically. And for the [DataType(DataType.MultilineText)]  annotation, it doesn't provide feature for setting rows and colums as well. So you have to write script code to add oninput event listener to change the style.
@model NewEvent

@ViewData["Title"]

Use this page to detail your site's privacy policy.

        @Html.LabelFor(m => m.Body, new { @class = "col-sm-2 control-label" })

            @Html.EditorFor(m => m.Body, new { htmlAttributes = new { @class = "form-control", placeholder = "placeholder" } })
            @Html.TextAreaFor(model => model.Body, new {cols = 2, rows = 5})
            @Html.ValidationMessageFor(m => m.Body)

    @section scripts {

    }


text:
Q: How to solve this integral $\int_0^{1}(2x^2+1)\sqrt{\frac{1-x^2}{1-x^8}}\ dx$ $$\int_0^{1}(2x^2+1)\sqrt{\frac{1-x^2}{1-x^8}}\ dx$$
substituting $x^4=\sin u; dx=\frac{\cos u}{4(\sin u)^{3/4}}$
$$\frac1{4}\int_0^{\pi/2}\frac{\left(2\sqrt{\sin u}+1\right){\sqrt{1-\sqrt{\sin u}}}}{(\sin u)^{3/4}}\ du$$
$$\frac 1{2}\int_0^{\pi/2}\frac{\sqrt{1-\sqrt{\sin u}}}{(\sin u)^{1/4}}du+\frac1{4}\int_0^{\pi/2}\frac{\sqrt{1-\sqrt{\sin u}}}{(\sin u)^{3/4}}\ du$$


text:
Q: Groovy + JPA + Spring not working I have the following java class:
package domain;

//imports

@Entity
public class User {

    @Id @GeneratedValue
    private long id;

    private String name;
    private String password;
    private String mail;
    //Getters, Setters and Constructors
}

When I change the file extension to .groovy, the application stops working. In fact it throws this stacktrace:

org.springframework.dao.InvalidDataAccessApiUsageException:
  Unknown entity: domain.User; nested
  exception is
  java.lang.IllegalArgumentException:
  Unknown entity: domain.User

I'm reading this book and the author states that any groovy class can take the place of a java class just changing its extension. So why does spring and JPA don't recognize my  groovy class?
Has anyone used this technologies successfully?

A: There's not a lot of info here, so time to guess.
Seems like Spring can't find the User.class file.  The Groovy and Java compilers may have different output paths, and the Groovy output path may not be in your classpath, or your deployment set.
Check your War, is User.class in it?  Is it in WEB-INF/classes/domain?  If not, then the Groovy output folder doesn't seem to be in your deployment.  Try changing the Groovy output folder to match your Java output folder.

A: Both Groovy (.groovy) and Java (.java) source files will compile to bytecode (.class) files. There's no file extension renaming necessary.
If you have groovy code, you need to use the groovy compiler to generate a .class file, much like a .java file will generate a .class file with javac.
It doesn't seem to be a JPA or Spring issue.


text:
Q: How many classes does the equivalence relation partition the set? Looking for help on B) How many classes does the equivalence relation partition set X

Consider the relations $R$ and $S$, defined on the set $X = \{1, 2, . . . , 99\}$ as follows.
$xRy \iff x + y$ is a multiple of $11$,
$xSy \iff x − y$ is a multiple of $11$.
A) One of $R$ and $S$ is an equivalence relation, the other is not. Determine which is which and justify your answers.
B) Into how many classes does the equivalence relation partition set $X$?

So far I've determined that S is the equivalence relation as R isn't reflexive or transitive. My only attempt at B is that there is 11-1=10 non-zero congruence classes, so does each one correspond to a non-zero equivalence class?
Any help is appreciated!

A: Just count them.
$1 R 12 R 23 R 34 R .... R 90$
$2 R 13 R 24 R 35 R .... R 91$
....
$10 R 21 R 32 R 43 R..... R 98$
$11 R 22 R 33 R 44 R ..... R 99$
That's 11.
It doesn't make any sense to subtract the "zero" equivalence class for 2 reasons.
1) The "zero" equivalence class is STILL an equivalence class so why they heck would you omit it?  NOWHERE in the question does it say ANYTHING about how many non-zero equivalence classes; it ask how many equivalence classes.  And $\{11,22,33,44,55,66,77,88,99\}$ is certainly an equivalence class, isn't it?
2) Since no method of "addition" has been defined or discussed, there is no meaning to defining any one of the equivalence classes as be a "zero" equivalence class.  IF we were to define $\{x|x R c\} + \{x|x R d\} = \{x| x R (d+c\pm 11k \text{ for some integer } k)\}$ and define $[0]$ as the equivelence clas so that $[0] + \{x|x R c\} = \{x|x R c\}$ then, yes, $\{11,22,33,44,55,66,77,88,99\} = [0]$.  But again, so what, it's still an equivalence class, isn't it?

A: To show $S$ is an equivalence relation you can either verify directly that it is reflexive, transitive, and symmetric or demonstrate that the relation partitions the set and use the fundamental theorem of equivalence relations. If you can demonstrate the existence of the congruence classes you have such a partition and that's sufficient to demonstrate that you have an equivalence relation. As you've deduced there are eleven such classes, and ten of them do not contain zero. I would also encourage you to consider the first method of directly verifying the three defining properties as it's both instructive and relatively easy.


text:
Q: How should I get started using PHPUnit as a testing framework for a bunch of functions and classes I have already made? I've already read the documentation. Basically I've tried tests while following the BankAccount example.
But I get errors:

Warning: require_once(PHP/CodeCoverage/Filter.php) [function.require-once]: failed to open stream: No such file or directory in [...]/unitTest/phpunit.php on line 38

Also, the PHP scripts seems to start with #!/usr/bin/env php which indicate they should be run from the console. I'd rather run these from the browser...
Suppose I have a function f1() that returns a string. How should the tests be made? Am I missing something?

A:
A short introduction to the test framework

PHPUnit provides a simple framework for creating a test suite to automate testing of functions and classes. PHPUnit is inspired by JUnit which was created by Kent Beck and Erich Gamma as a tool for eXtreme Programming. One of the rules of XP is to test small software components as often and early as possible, this way you will not have to fix bugs and errors in the API while setting up and testing larger applications which depend on the class. While unit testing is one of the fundimental rules in XP, you don't have to switch to XP to benefit from PHPUnit. PHPUnit stands alone as a good tool for testing classes or a set of functions and will ease your development cycle and help you to avoid endless debug sessions.

Work routine

Normally, you would write a class, do some unsystematic tests using echo() or var_dump(). After this, you use the class in your application and hope everything is ok. To benefit from PHPUnit you should rethink the flow. The best way is to do this:

*

*design your class/API

*create a test suite

*implement the class/API

*run the test suite

*fix failures or errors and go to #4 again

It may seem that this will require a lot of time, but this impression is wrong. Creating the test suite using PHPUnit needs only a few minutes and running the test suite only seconds.

Design a class

Let's start with a small example: a string class. First we create a bunch of functions declarations to work on a string:
---- string.php ----

<?php
class String
{
    //contains the internal data
    var $data;

    // constructor
    function String($data) {
        $this->data = $data;
    }

    // creates a deep copy of the string object
    function copy() {
    }

    // adds another string object to this class
    function add($string) {
    }

    // returns the formated string
    function toString($format) {
    }
}
?>

Creating test suite

Now we can create a test suite, which checks every function of your string class. A test suite is normal PHP class inherited from PHPUnit_TestCase containing test functions, identified by a leading 'test' in the function name. In the test function an expected value has to be compared with the result of the function to test. The result of this compare must delegate to a function of the assert*()-family, which decides if a function passes or fails the test.
---- testcase.php ----

<?php

require_once 'string.php';
require_once 'PHPUnit.php';

class StringTest extends PHPUnit_TestCase
{
    // contains the object handle of the string class
    var $abc;

    // constructor of the test suite
    function StringTest($name) {
       $this->PHPUnit_TestCase($name);
    }

    // called before the test functions will be executed
    // this function is defined in PHPUnit_TestCase and overwritten
    // here
    function setUp() {
        // create a new instance of String with the
        // string 'abc'
        $this->abc = new String("abc");
    }

    // called after the test functions are executed
    // this function is defined in PHPUnit_TestCase and overwritten
    // here
    function tearDown() {
        // delete your instance
        unset($this->abc);
    }

    // test the toString function
    function testToString() {
        $result = $this->abc->toString('contains %s');
        $expected = 'contains abc';
        $this->assertTrue($result == $expected);
    }

    // test the copy function
    function testCopy() {
      $abc2 = $this->abc->copy();
      $this->assertEquals($abc2, $this->abc);
    }

    // test the add function
    function testAdd() {
        $abc2 = new String('123');
        $this->abc->add($abc2);
        $result = $this->abc->toString("%s");
        $expected = "abc123";
        $this->assertTrue($result == $expected);
    }
  }
?>

The first test run

Now, we can run a first test. Make sure that all the paths are correct and then execute this PHP program.
---- stringtest.php ----

<?php

require_once 'testcase.php';
require_once 'PHPUnit.php';

$suite  = new PHPUnit_TestSuite("StringTest");
$result = PHPUnit::run($suite);

echo $result -> toString();
?>

If you call this script from the commandline, you will get the following output:
TestCase stringtest->testtostring() failed: expected true, actual false
TestCase stringtest->testcopy() failed: expected , actual Object
TestCase stringtest->testadd() failed: expected true, actual false

Every function fails the test, because your string functions didn't returned what we defined as the expected value.
If you want to call the script through your browser, you have to put the script in a correct html page and call $result->toHTML() instead of $result->toString().

Implementation

Ok, let's start with implementation of the our string class.
---- string.php ----

<?php
class String
{
    //contains the internal data
    var $data;

    // constructor
    function String($data) {
        $this->data = $data;
    }

    // creates a deep copy of the string object
    function copy() {
        $ret = new String($this->data);
        return $ret;
    }

    // adds another string object to this class
    function add($string) {
        $this->data = $this->data.$string->toString("%ss");
    }

    // returns the formated string
    function toString($format) {
        $ret = sprintf($format, $this->data);
        return $ret;
    }
}
?>

The implementation is complete and we can run the test again:
~>
php -f stringtest.php

TestCase stringtest->testtostring() passed
TestCase stringtest->testcopy() passed
TestCase stringtest->testadd() failed: expected true, actual false

D'oh! the last test failed! We made a typing mistake. Change line 16 in string.php to
<?php
$this->data = $this->data.$string->toString("%s");
?>

and run the test again:
~>
php -f stringtest.php

TestCase stringtest->testtostring() passed
TestCase stringtest->testcopy() passed
TestCase stringtest->testadd() passed

Everything is now OK!

Conclusion

Does it seem like a lot of work for testing three simple functions? Don't forget, this is a small example. Think about bigger, more complex API's like database abstraction or basket classes in a shop application. PHPUnit is an excellent tool to detect errors in the implementation of your class.
Often you will want to reimplement or refactor a large class which is used in several different applications. Without a test suite the likeliness of you breaking something in one of the applications that depends on your class is very high. Thanks to unit tests, you can create a test suite for your class, and then reimplement your class with the security of knowing that as long as the new class passes the tests, applications that depend on the class will work.
Used source: http://pear.php.net

A: I would really recomment running PHPUnit from Command Line, if possible. At our Company, it is not possible, but we are trying, wich makes our Tests unstable ...
I assume you have to setup some include paths for php with set_include_path(), so phpunit finds the rest of your files. But that may not be enough ...
Our code looks something like this
// you will have to write your own class here that collects the tests
$collector = new Unit_Test_Collector();
$suite = $collector->getSuite();

//$config is an array of phpunit config options

PHPUnit_TextUI_TestRunner::run($suite, $config);


text:
Q: Java 6 Copy files with readline I try to copy files with some mandatory parameters : inputEncoding, outputEncoding and outputLineSeparator.
But when I run my following code, my file with the CRLF final char is not well copy, this last CRLF char disapear.
I think readLine return null after line 3 because line 4 is empty...

My goal is to find the copyfile function that could strictly copy this two following files.

Is there a way to copy also this final empty line (the last newline char) ?

Thanks in advance for any help.

Input Files
File testInEndNL.txt(explicit char)
A<CRLF>
B<CRLF>
C<CRLF>

File testOutEndEOF.txt(explicit char)
A<CRLF>
B<CRLF>
C

Output Files
File testOutEndNL.txt(explicit char) KO for me
A<LF>
B<LF>
C

File testInEndEOF.txt(explicit char) OK for me
A<LF>
B<LF>
C

Code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class TestEncoding {

    public static void main(String[] args) {
        File src;
        File dst;
        Charset inputEncoding;
        Charset outputEncoding;
        String outputLineSeparator;

        inputEncoding = Charset.defaultCharset();
        outputEncoding = Charset.forName("UTF-16");
        outputLineSeparator = "\n";

        src = new File("C:\\Users\\Dam\\Desktop\\testFiles\\testInEndNL.txt");
        dst = new File("C:\\Users\\Dam\\Desktop\\testFiles\\testOutEndNL.txt");
        copyFile(src, dst, inputEncoding, outputEncoding, outputLineSeparator);

        src = new File("C:\\Users\\Dam\\Desktop\\testFiles\\testInEndEOF.txt");
        dst = new File("C:\\Users\\Dam\\Desktop\\testFiles\\testOutEndEOF.txt");
        copyFile(src, dst, inputEncoding, outputEncoding, outputLineSeparator);

    }

    private static void copyFile(File src, File dst, Charset inputEncoding, Charset outputEncoding, String outputLineSeparator) {
        try {
            String oldLineBreak = System.setProperty("line.separator", outputLineSeparator);
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), inputEncoding));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), outputEncoding));
            String line = reader.readLine();
            if(line != null) writer.write(line);
            while ((line = reader.readLine()) != null) {
                writer.newLine();
                writer.write(line);
            }
            reader.close();
            writer.close();
            System.setProperty("line.separator", oldLineBreak);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

A: The short answer is that you can't do it with .readLine(), because it strips off the end-of-line characters.
You will need to use .read() instead, which will read in character by character, and do your own EOL processing. This returns an int, but you can cast it to a char:
char c = (char)reader.read();

A CR/LF will come out as two separate characters, so you'll have to watch for that and process accordingly. If you know that your files will only have either CR/LF or just LF, then it's a little easier, because whenever you read a CR you know an LF is following straight behind.
The bytes you're reading won't vary. You'll be reading them as UTF-8 by default, which will always encode CR and LF as single byte characters. In int terms, they'll come out as 13 and 10 respectively.


text:
Q: Javascript generate AES using cap and small cap letters I'm setting up the code to generate the AES hash using with 3 random numbers to generate the hash, but I don't want to generate the hash that come with the keys such as like ?, /, +, =...etc.
Here is the output for the hash that I use to generate it:
U2FsdGVkX1+nF+bhzvA/sFnQKgOKwrRNJbqr+XzJ/2k=

I want to generate the AES hash that start with FM cap letters with the long random cap and small cap letters to make it to show like this:
FMfcgxwCgCRTpGWxctmfLpRBZxVcrkdM

Here is what I use to encrypt and decrypt the hash:
//encrypt the hash
var hash = '234';
var encryptedAES = CryptoJS.AES.encrypt(hash, "My Secret Passphrase");

//decrypt the hash
var decryptbytes = CryptoJS.AES.decrypt(hash.toString(), "My Secret Passphrase");
var email_number = decryptbytes.toString(CryptoJS.enc.Utf8);

What I'm expecting to do is to encrypt the hash using with the long random cap and small cap letters like FMfcgxwCgCRTpGWxctmfLpRBZxVcrkdM without the keys ?, -, = or whatever it is and I want to decrypt the hash to go back to numbers that I enter when I encrypted it.
Can you please show me an example how I could use CryptoJS.AES.encrypt to encrypt the numbers to turn into 32 letters that start with FM with the cap and small cap letters?
Thank you


text:
Q: Google Font has a different appearance in Gmail on Mobile and Desktop than what it really is Why does google font appear different in Website, Gmail App on Phone and Gmail on desktop? I am using Merienda One font and to my surprise it's not same everywhere. I am sure this would be issue with different fonts or all fonts but let's talk about this one now as a reference as I am using it.
Code
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Lovely

Actual Font on Google Fonts

*

*On Gmail Desktop

*On Gmail Android

I want to fix this. I want the original appearance of the font everywhere. What is the solution?


text:
Q: Regular Expression inside a MySQL Like value Reg ex again.
Trying to run a like SQL query:
mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:3:\"{$id}\"%'");

problem is the length value will be unknown, only the ID.
Of course, I could use strlen($id) and do this:
$len = intval(strlen($id));
mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:{$len}:\"{$id}\"%'");

But I dont really care to check the len value, there's gotta be a bit of Reg ex to match anything where the length will be and sort this without having to calc the length before.
mysql_query("SELECT * From tablename WHERE somthing LIKE '%id|length:^*:\"{$id}\"%'");

ideas?

A: @Naddiseo's link is a good one, I recommend you use REGEXP. What do you mean by 'No exact example matching'?
Try something like (I added in the newlines for readability):
mysql_query("SELECT * From tablename
             WHERE somthing
             REGEXP '^.*id\\\|length:[0-9]+:\"{$id}\".*$'");

The relevant regex without worrying about escaping for MYSQL/php strings is
^.*id\|length:[0-9]+:"abc".*$

(assuming abc is a particular ${id}).
It says, "look for anything followed by the literal string id|length: (I've escaped it as | has a special meaning in regex and you want literal |), followed by numbers ([0-9]+) being the length of the id, followed by :"{$id}" and anything else (where {$id} has been substituted in).
Now, if you read the MySQL regexp page that @Naddiseo quoted, you'd see that any backslashes need to be further escaped as MySQL parses backslashes as special characters.
So, if you were to enter this query into a MySQL command line (let's assume {$id} is abc for now), you'd have to type:
SELECT * From tablename
  WHERE somthing
  REGEXP '^.*id\\|length:[0-9]+:"abc".*$'

Now, since you are calling this from PHP inside double quotes, you need to escape your backslashes again to make sure the right number get through to MySQL, as well as backslashing your double quotes to escape them. Hence the three backslashes in the mysql_query above before the |.


text:
Q: Why is [object Object] viewed in column when trying to bind columns in MVC This is the JS I call in Index on document ready
jsonfields = @Html.Raw(Json.Encode(ViewBag.ColumnData));

This is the Ajax Call which I Make to bind
function onTeamTreeLoad(e) {
    try {
        $.ajax({
            type: "POST",
            url: window.ApplicationPath + 'Generic/GetTeamTree',
            dataType: "json",
            headers: { "__RequestVerificationToken": $("#AntiForgeryToken").val() },
            contentType: 'application/json',
            success: function (data) {
                if (data != null) {
                    $("#TeamName").kendoDropDownTree({
                        dataSource: {
                            schema: {
                                model: {
                                    children: "Items"
                                }
                            },
                            data: data
                        },
                        dataTextField:  "Text",
                        dataValueField: "Id"
                    });

                    try {
                        if (e.model.TeamName !== "") {
                            $("#TeamName").data("kendoDropDownTree").text(e.model.TeamName);
                        }
                    } catch (e) { }
                }
            },
            error: function () {
                console.log('Failed to load');
            }
        });
    } catch (e) {
        console.log(e);
    }
}

Why am I seeing [objectObject] when trying to bind the column? I want the data to be viewed instead of objectObject. I tried adding SerializeObject method to ID and Text but then I could not view that column when editing! I would like to know if there is any mistake in the AJAX call and what are the things that need to be added if using SerializeObject or JSON.Stringify.

A: Here you are just printing object. So Object -> Stringify give output like [object Object].
You can try this code.
for(var prop in obj) {
  console.log(obj[prop]);
}


text:
Q: How to handle formData with Angular-Payments I'm making use of Angular-Payments in my AngularApp. After passing all the data to Stripe, I would like to store the users credit cards last 4 digits on my server. I'm having trouble accessing the form data so that I can get the last 4 digits from the card number.
My code is as follows
html:
      <form stripe-form="handleStripe" role="form" ng-if="authenticated" name="takeMoneyForm" ng-submit="takeMoney(takeMoneyForm, model)">
            Name on Card
            <input type="text" class="form-control" name="card_name">

            Card Number
            <input type="text" class="form-control" name="card_number" ng-model="number" payments-validate="card" payments-format="card" payments-type-model="type" ng-class="takeMoneyForm.number.$card.type">
      </form>

Controller code to accept & submit form:
  $scope.takeMoney = function(formData, model){
    $scope.handleStripe = function(status, response){
      if(response.error) {
        alert("Error happened")
      } else {
        var dataModel = {
          email: model.email,
          profile: {
            stripe_token: response.id,
            last_4_digits: "how can I get the cards last 4 digits here??",
            stripe_id: 'df'
          }
        }
        djangoAuth.takeMoney(dataModel)
      }
    }
  }

A:   last_4_digits:  response.card.last4

https://stripe.com/docs/stripe.js?
You can also pull the information on your server using the token.
https://stripe.com/docs/api#tokens

A: Sending the token to Stripe directly doesn't actually charge the card. To charge the user's card, you have to send the token to a script on your server, which Stripe provides various libraries for. It's this step that allows you to rip out whatever data was in the token and then save the details to your server and then send the charge to Stripe according the the API.
Here is the page that give examples of the server-side scripts for this step: https://stripe.com/docs/tutorials/charges


text:
Q: Passing values from another form Winforms All the tutorial in passing forms in the web are all from form1 then open form2 and then pass the value.
I want something reverse. form1 and form 2 is open so if you click ok in form2 the value you get in form 2 will be passed in form 1.
ex. form1 click buttton openform2button (form 2 shows) write 7 (number 7) on a textBox (in form2) click button okbutton then form 2 closes after form2 closes the textbox in form1 will store the data in form2. so the 7 you will put in textbox form2 will be saved and transferred in textbox form1. is that possible?

A: There's a number of ways you could do it:

*

*Share a model object between form1 and form2.

*Have form2 expose an event that form1 subscribes to. Pass the values in the event args.

*Have form2 expose the value as a public property that form1 reads after form2 closes.

A: You can just have a public property on Form2 that Form1 will access when it needs to see the value. Something like this:
using(Form2 form2 = new Form2())
{
  if(form2.ShowDialog() == DialogResult.OK)
  {
    form1Logger(form2.NumberWritten);
  }
}

The property can be something as simple as this:
class Form2
{
     public String NumberWritten
     {
         get{return textBox.Value;}
     }
}


text:
Q: Training model on AWS Deep Learning AMI instance - gets 'killed' with warnings I am trying to train inception ResNetV2 model on my own dataset on Amazon's Deep Learning AMI
When I try to train on local machine the training starts as usual but when I try to train on aws instance it gets killed.
First I tried to train with MXNET backend . It gave the following error :

Notice that it gets killed.
So in
nano ~/.keras/keras.json

I tried to set image data format to channels_first :
{
    "image_data_format": "channels_first",
    "backend": "mxnet"
}

Then I got the error:
Traceback (most recent call last):
    File "train.py", line 17, in <module>
        model = applications.inception_resnet_v2.InceptionResNetV2(include_top=False, weights='imagenet', input_shape = (img_width, img_height, 3))
    File "/home/ubuntu/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/keras_applications/inception_resnet_v2.py", line 243, in InceptionResNetV2
weights=weights)
    File "/home/ubuntu/anaconda3/envs/mxnet_p36/lib/python3.6/site-packages/keras_applications/imagenet_utils.py", line 296, in _obtain_input_shape
'`input_shape=' + str(input_shape) + '`')
ValueError: The input must have 3 channels; got `input_shape=(182, 182, 3)`

Then I tried to switch to tensorflow backend to see how it plays out because there might be some misunderstanding on my part on how this process works. But when I switched to tensorflow backend and started training I got the following error :

As you can see it gets killed again.
I am not sure what to do next. Some help would be great.
P.S I am sorry for the screenshots. You're going to have to zoom in a little to get a better view.

A: Deep Learning AMI was mostly not supported on t2 instance type. It should work on most of the good cpu instance type (like C4, C5) or GPU instance type (G3, P2 and P3) and many other instance type.


text:
Q: CKEditor 3.x - Dynamically add UI elements to plugin dialog I'm building a CKEditor 3.x plug-in that allows certain sections of HTML to be conditionally displayed by a separate viewer application that is tied in to our back-end systems. My CKEditor plug-in will be used to define these conditions, but I'm getting stuck on how to dynamically add UI elements to the plug-in dialog.

After I select the 'AND' option in the last select UI element (see the screenshot), I want to dynamically add another 3 select UI elements, similiar to the first 3 select's.
I've trawled through this forum and the plug-in tutorials and I haven't been able to figure it out. All the examples I looked at only have static dialog definitions. Any help with this would be appreciated.

A: You can add an iFrame with an external page that you can customize using a set of usual and easier tools like jQuery (javascript) and your server-side programming language.
In some cases you would like to make sure that the iFrame's content will not be cached by appending some random text in the query string. Then iframe page can communicate with the dialog by calling parent.*

A: Currently I'm working with CKEditor, too. Though our problem is not exactly alike, my approach is to use a component in the plugin dialog that contains a div. Then, in onShow, I will load a certain page to the div.
I find it easier since I can manipulate that certain page more freely (like dynamically add UI element).
But there is a problem with this approach. CKEditor never deletes its dialog divs. So if after browsing other pages and then going back to the editor page, a click on the plugin button will duplicate dialog div (which contain the page in which I do my manipulation).
I'm still looking for the solution or perhaps another way to do this. I'll try to update my answer if I've got something.

A: As Denis Volovik mentioned, this can be achieved using an Iframe with an external page. This is exactly what I did a while ago to resolve my issue. Apologies for only posting it now, but here is some skeleton code of how I accomplished this:
function iframeDialog(editor) {
    return {
         title : 'someTitle',
         minWidth : 820,
         minHeight : 100,
         maxHeight: 200,
         contents :
               [
                  {
                     id : 'someTab',
                     label : '',
                     expand : true,
                     elements :
                           [
                              {
                                 id : 'myIframe',
                                 type : 'iframe',
                                 src : 'my_dialog_contents.html',
                                 width : '100%',
                                 height : 200,
                                 onContentLoad : function() {
                                        //...

                                    var iframe = document.getElementById(this._.frameId);
                                    iframeWindow = iframe.contentWindow;
                                    // can now call methods in the iframe window
                                 }
                              }
                           ]
                  }
               ],
         onShow : function() {
            // check if should display dialog, do dialog.hide if not
         },
         onOk : function()
         {
            var myIframe = this.getContentElement('someTab', 'myIframe');
            var iframeWindow = document.getElementById(myIframe.domId).contentWindow;
            var iframeDocument = iframeWindow.document;

                        // can now interrogate values in the iframe, call javascript methods

                        // can also call editor methods, e.g. editor.focus(), editor.getSelection(),
        }
    };
}

CKEDITOR.dialog.add( 'mydialog', function( editor )
{
    return iframeDialog(iframeDialog);
} );


text:
Q: Using sliders to make an image greyscale JS/HTML/CSS I am trying to use sliders to make an image grey using only pure JavaScript, HTML and CSS.
The user uploads a file which is then put onto a canvas. Then I would like the user to be able to move the slider on the range input and depending on the value of the range, it will change how close to black and white the image becomes.
Any help would be greatly appreciated.

let imageLoader = document.getElementById('imgFile');
imageLoader.addEventListener('change', handleImage, false);
let canvas = document.getElementById('imgCanvas');
let ctx = canvas.getContext('2d');

function handleImage(e) {
  let reader = new FileReader();
  reader.onload = function(event) {
    let img = new Image();
    img.onload = function() {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
    }
    img.src = event.target.result;
  }
  reader.readAsDataURL(e.target.files[0]);
}
<label for="img">Select image:</label>
<input type="file" id="imgFile" name="imgFile" accept="image/*">

<canvas id="imgCanvas" width="300" height="300"></canvas>
<label for="greyPic">Edit the greyscale: </label>
<input id="greyPic" type="range" min="10" max="100" value="100">

A: var slider = document.getElementById("greyPic");
var pic = document.getElementById("imgCanvas");

// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
    var value = this.value;
    //add grayscale based on the value of the slider
    pic.style.filter= `grayscale(${value}%)`;
}


text:
Q: Executing Groovy script from Maven When executing Groovy script from Maven I get the following error:

[ERROR] Failed to execute goal org.codehaus.groovy.maven:gmaven-plugin:1.0:execute (default) on project /path/to/project: org.codehaus.groovy.runtime.metaclass.MissingPropertyExceptionNoStack: No such property: project for class: /path/to/groovy/script/Example -> [Help 1]

I searched for possible cause and solution, but still don't understand what am I doing wrong and how to fix it. My script works fine when I execute it standalone or via ANT script.
Here is the script:
class Example {
   public static void main(String[] args){
       new Example().show();
   }

   def show() {
       println 'Hello World'
  }
}

And this is how I am calling it:
<dependencies>
    <dependency>
        <groupId>org.codehaus.gmaven.runtime</groupId>
        <artifactId>gmaven-runtime-1.7</artifactId>
        <version>1.3</version>
        <exclusions>
             <exclusion>
                 <groupId>org.codehaus.groovy</groupId>
                 <artifactId>groovy-all</artifactId>
             </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>1.7.6</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.groovy.maven</groupId>
            <artifactId>gmaven-plugin</artifactId>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>execute</goal>
                    </goals>
                    <configuration>
                        <source>${pom.basedir}/path/to/script/Test.groovy</source>
                    </configuration>
                </execution>
            </executions>
        </plugin>

A: Add your scripts directly to Example.groovy file, as long as you are able to access the default variables, instead of making it a POGO.
The script eventually compile down to a groovy class by itself with the same name as the file name (in this case Example). I am skeptical about the whole idea of class and psvm. :-)
//Example.groovy
println 'hello world'

println "$project"
println "$session"
println "$settings"

A: For whatever reason the gmaven-plugin does not appear to like a main
if you code it like
class Example {
   def show() {
       println 'Hello World'
   }
}
new Example().show();

it will work.


text:
Q: Добавление фото в поиске гугл возле своего сайта Как это сделать. В интернете все статьи 2014 года в которых говорится, что способ реализовать это через Google+ не работает.

A: К сожалению, Google перестает поддерживать функцию указания авторства в результатах выдачи. Фотография, а также другая информация об авторе в ближайшее время перестанет отображаться в расширенных сниппетах к статьям в SERP. Эту новость сообщил сотрудник поискового гиганта Джон Мюллер на странице в Google+: "мы пришли к выводу, что данная информация в результатах выдачи не несёт никакой практической выгоды нашим пользователям и даже отвлекает их от работы с результатами выдачи" (C) 2014 год


text:
Q: Add array to array with PHP in JSON I'm using the PHP code below to generate a JSON call.
$Services = array();

$ServiceList[] = array(
  'Name' => 'ideal',
  'Action' => 'Pay'
);
$postArray["Services"]["ServiceList"] = $ServiceList;

$Parameters[] = array(
    'Name' => 'issuer',
    'Value' => 'ASNBNL21'
);
$postArray["Services"]["ServiceList"]["Parameters"] = $Parameters;

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);

But when I generate the array "Servicelist" it gives me the wrong JSON code. It shows  "0": { instead of the array braces.
"Services": {
        "ServiceList": {
            "0": {
                "Action": "Pay",
                "Name": "ideal"
            },
            "Parameters": [
                {
                    "Name": "issuer",
                    "Value": "ASNBNL21"
                }
            ]
        }
    }

The right JSON code should look like this:
"Services": {
    "ServiceList": [
      {
        "Name": "ideal",
        "Action": "Pay",
        "Parameters": [
          {
            "Name": "issuer",
            "Value": "ABNANL2A"
          }
        ]
      }
    ]
  }

A: Instead of starting on the top level, start with the innermost level:
$parameters = [ 'Name' => 'issuer', 'Value' => 'ASNBNL21' ];
$serviceList = [ 'Name' => 'ideal', 'Action' => 'Pay', 'Parameters' => [ $parameters ] ];
$services = [ 'ServiceList' => [ $serviceList ] ];
$postArray = [ 'Services' => $services ];

$postjson = json_encode($postArray, JSON_PRETTY_PRINT);


text:
Q: Get DefaultListModel to use LinkedList Is it possible to make a DefaultListModel use the contents of a LinkedList to display?
This is then to be used with a JList.

A: Yes it is possible: You simply need to subclass AbstractListModel and override getElementAt and getSize to call through to your underlying LinkedList.
public class MyListModel extends AbstractListModel {
  private final List<?> l;

  public MyListModel(List<?> l) {
    this.l = l;
  }

  public Object getElementAt(int index) {
    return l.get(index);
  }

  public int getSize() {
    return l.size();
  }
}

Warning: When implementing ListModel or TableModel and backing the model with a List I would advise using ArrayList over LinkedList to ensure O(1) access time when accessing a given element.

A: DefaultListModel uses a Vector as the backing list. This is a private member, so you don't really have an option extend and override how it works. If you have to use a LinkedList, you'll probably have to write your own list model implementation (say, extend AbstractListModel as the default list model does), or loop through your list and add each object to the list model.

A: Unless you subclass it and override all of the implemented methods, no. but you can add all of the elements from a LinkedList to the DefaultListModel (populating the underlying Vector)
for (Object element : linkedList)
    model.addElement(element);

or just write your own implementation of AbstractListModel using a LinkedList/List/Collection as the source.


text:
Q: Twitter API - How to store JSON in Array? I'm trying to get the number of followers, follows, tweets, etc. for a user.
I found this api call http://api.twitter.com/1/users/show.json?screen_name=barackobama
How do I take that json result and store it in an array?
Thanks

A: You can use json_decode and set the second parameter to true:
$json = file_get_contents("http://api.twitter.com/1/users/show.json?screen_name=barackobama");
$json_array = json_decode($json, true);

Of course for file_get_contents() to work with an URL, you have to have allow_url_fopen directive enabled in your php.ini.


text:
Q: Rails: redirect_to don`t redirect to subdomain I try to redirect user to custom domain. Code below:
def redirector
    user = User.find(1)
    redirect_to posts_path(:subdomain => user.domain)
end

But user will redirected to host domain (site.com) without subdomain. Dev log:
User Load (0.6ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = '1' LIMIT 1
Redirected to site.com/posts

Using Rails 4.1.4 with ruby 2.1.2

A: You probably need to additionally specify the tld_length.
More information at: http://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for


text:
Q: log4j2 ERROR exception adding carriage returns? I'm using the log4j exception logging syntax like
log.error("Exception: ", e);

Seems to me the log4j is inserting a carriage return to separate the message and the throwable. Can see the circled ^M below. Anyone know how I could have that log as a normal newline instead? (so it would look like logging statement preceding it)

A: If you want to have the stacktrace, I believe that is the expected output. If you want the exception message itself, you can access it with e.getMessage(). In your case, you could eliminate the Exception: string as you're already logging it at the error level and log it as log.error(e.getMessage(), e).

A:
Anyone know how I could have that log as a normal newline instead?

You could construct the message yourself and pass that message as the sole argument to the log.error(...) method. As it is, you are passing 2 parameters, a message and a Throwable.  The message is written to the log output, and the the stack trace is written as a separate thing.  That is by design and what most folks want.  If that is not what you want, don't pass the Throwable and construct your own message.


text:
Q: How can we connect to remote spark cluster via jupyterhub? First of all my agenda is to be able to use spark codes inside jupyterhub. In other words I want to connect a remote spark cluster to jupyterhub. After searching about it I came up with two solutions:1)Livy and 2)spark magic. I have tried Livy but since it doesn't support spark version 3 I have put that one aside, also another way we considered was via spark magic but we couldn't install or even find a good documentation about it.
what came into our minds was somehow merge the two image of spark and jupyterhub together to gain what we need.
Does anyone have any idea how it can be done or a better suggestion?
Even a good documentation about spark magic that we can use would be wonderful.
thank you for your help.


text:
Q: Merge lists in Lisp I am trying to take a list representing a binary search tree and output a list elements in order so (displayBST '(10(5(3(2()())())())())) -> (2 3 5 10). All I can seem to mange to get is  list looking like (((2 3) 5) 10) and I am not sure how to make all numbers base elements.
(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (first elements))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (list (displayBST(second elements)) (first elements))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (list (first elements) (displayBST(third elements))))))))

A: Think about how you join a given element to the value returned recursively by the function. If you want X + Y = (X Y) you should use (cons X (list Y)). Therefore the base case (i.e. (null (second elements)) and (null (third elements)) should return (list (first elements)).
What you want is something like this:
(let((SUMS))
(defun displayBST(elements)
 ;IF NO ELEMENTS return SUMS

 (cond((null elements)
           nil)
      ;if both branches null return first element
      ((and(null (second elements))(null (third elements)))
            (print (first elements))
            (list (first elements)))
      ;if left branch not null
      ((not(null (second elements)))
            ;if right branch null
            (cond((null (third elements))
                      ;set SUMS to (left branch) and first element
                      (setf SUMS (append (displayBST(second elements)) (list (first elements)))))
                   ;else set SUMS to (left branch) and first element and (right branch)
                  (t(SETF sums (append (displayBST(second elements))(first elements)(displayBST(third elements)))))))
      ;if left branch null and right not null
      ((not (null(third elements)))
           ;set SUMS to first element and (right branch)
           (setf SUMS (cons (first elements) (displayBST(third elements))))))))


text:
Q: How to identify and remove unused files / directories from an apache web server New Customer. Old server. Unused Files & Directories abound. 5 specific core directories (attached to differing domains). 10-20 possible extraneous directories w/ files on the same level as the core directories.
Creating something to run in each core directory and do the following:
A script that reduces a few months worth of raw log files down to just the URI, gathers a directory listing, loops through the directory listing and lists everything without a corresponding appearance in the condensed log file.
Anything like that exist already? Better method of accomplishing end goal? Suggested language / tools to build?
Honestly, I'm looking for where to begin on this if it were done right.

A: Honestly, I'm looking for where to begin on this if it were done right.
With a good backup and a new server, built with only what you need.
The danger of removing stuff based on access is that you'll lose the long tail stuff (that one super-critical file that is accessed twice a year by your vendor in Tahiti, without which they can't ship your shiny widgets to you and the entire company goes belly-up).  This is where the backup comes in (so you can get the shiny widgets file back).
The danger of trying to "clean up" an old server filled with cruft is not knowing what's cruft and what's important.
Since you're asking us this question instead of shoving your fist into the server and tearing out its rotting digital guts we can assume you don't know for certain what is/isn't cruft.  Even the best tool will have fuzz on one side or the other: Either you will leave cruft because you don't know if you need it, or you will remove something you need and have to go for those backups.

If you still want to write the script you described you can do it with a (relatively) simple shell script:

*

*cat the log files together

*use awk to grab the URLs

*sort and uniq the URL list to eliminate duplicates

*

*You may need to do further awk and sed manipulation to turn URLs into filenames on-disk...

*Take your list of known-accessed files, review it manually & add in anything your scripts may have missed

*tar up the known-accessed files and stuck them somewhere safe.

*Move the old directory aside (keep it safe as a backup) & untar your known-accessed files.

(Implementation is left as an exercise for the reader, mostly because your access log format may be different than mine which affects the awk expression(s) you need to use to turn URLs into files on the filesystem)


text:
Q: bibLaTeX: Custom \citep style For days I've been messing around now with the otherwise great biblatex package but, alas, I am overwhelmed by all the technical mumbo-jumbo in its documentation. The thing I want to do is (hopefully) quite simple:
I want a citation with page-number and parentheses such as this one
``Some quote'' \citep[185]{author:book}

to look like this:

"Some Quote" (Author 2001: 185)

I tried a number of citestyles but I never come even close to that, it always looks something like this:

"Some Quote" (Author, 2001, 185)

Sorry for the probably dumb question but this menial detail is costing me a lot of nerves :(

A: If you prefer to stick with biblatex, this is an easy modification (although it is true that the biblatex manual can be overwhelming at first [and second] glance).
Try this:
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage[style=authoryear, backend=biber, natbib]{biblatex}
\addbibresource{biblatex-examples.bib}% ships with biblatex

\renewcommand*{\postnotedelim}{\addcolon\addspace}
\renewcommand*{\nameyeardelim}{\addspace}

\begin{document}

% note: the 'natbib' option gives you access to natbib-like commands
``Some quote'' \citep[185]{doody}.
According to   \citet[33]{aristotle:anima}, \ldots.

% compare these:
``Some quote'' \parencite[185]{doody}.
According to   \textcite[33]{aristotle:anima}, \ldots.

% and \autocite
``Some quote'' \autocite[185]{doody}.
According to   Aristotle \autocite*[33]{aristotle:anima}, \ldots.

\printbibliography
\end{document}

Note, if you are going to use biblatex, I recommend you also make use of csquotes, which was developed by the same package author.


text:
Q: how to paste a line instead of a string across many files I have 1000 files with txt format, I want to
I want to replace the first line of each file which is "PUT KEYWORDS HERE"
with my keywords which is "XYZ LET DDMIN=0.0 SCFCRT=1.D-10"
any idea

A: sed -i "/PUT KEYWORDS HERE/c\XYZ LET DDMIN=0.0 SCFCRT=1.D-10" path/to/file/*.txt

A: Try this
#!/bin/bash

files=$(ls -lA ./path | grep -v "total" | awk {'print $NF'})

for file in ${files[*]}
do
    sed -i -e '1s/PUT KEYWORDS HERE/XYZ LET DDMIN=0.0 SCFCRT=1.D-10/' ./path/$file
done


text:
Q: The date modified of a deleted file in a disk image is having a later date than the last system Log On date I am analyzing a disk image for a forensic investigation and I see deleted files having a later date for  last modified date than the last system log on date.
Does this means someone has created a raw image file and delete those files from the forensic image and then burn it to the disk again.
Can some one do this using a linux live CD.


text:
Q: Value of one TextInput changes when user change value of other I create a weight calculator where user can enter weight in KG or LB and value of the other input will change automatically. For example: user enter in KG input 100 and LB accepts value 198. I tried to give to TextInputs's default value value of entered input, but it doesn't work.
Can somebody help me?

A: If I understand you correctly: you are making a converter for KG and LB,
you have 2 input fields, when you change the value in first, you want to show the result in the second (vise versa).
If you want to change values in input fields you need to have controlled components which means you will set values with your state values.
For a short example (in ReactJS but the concept is the same):
import React from "react";

export default class Converter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value1: 0,
      value2: 0
    };
  }

  onChangeValue1 = value1 => {
    this.setState({ value1: value1, value2: value1 * 2 });
  };

  onChangeValue2 = value2 => {
    this.setState({ value1: value2 / 2, value2: value2 });
  };

  render() {
    return (
      <div>
        <input
          value={this.state.value1}
          onChange={e => this.onChangeValue1(e.target.value)}
        />
        <input
          value={this.state.value2}
          onChange={e => this.onChangeValue2(e.target.value)}
        />
      </div>
    );
  }
}


text:
Q: Is it a pattern of concurrent programming? Some OOP design appeared in my head. It's like a pool and a factory.
The factory creates resources that can be shared between multiple threads.
One resource entity is expensive and its creation takes many time.
A resource can be used by multiple threads at one time.
In my particular case a resource is a SSH connection. SSH connection uses one TCP socket.
But one SSH connection can have multiple sessions.
Each thread creates new session for itself.
Session creation doesn't require to work with the factory.
Multiple threads can try to interact with the same remote host.
I defined statuses for a resource:
init  some thread tried to get SSH connection but it doesn't exists.
      there is a long process of resource creation. If another thread will try
      to get the same resource too it gets that the required resource is on the progress
      and the second thread goes to wait a notification.
free  all sessions are closed and no thread uses the SSH connection
busy  at least one thread has taken the SSH connection
closed tcp socket is destroyed
There is a state diagram of a resource:

*

*-> init -> busy -> free -> closed
free -> busy
I read books about OOP patterns, enterprise application patterns, concurrent patterns
but I cannot remember a situation that I described above.
SSH is just example. This pattern fits to any heavy resource that supports
concurrent work. When second thread wants to get creating resource but creation
second instance of resource is nonsense.
If it's a pattern then what's his name?
I confident this design is already described somewhere.

A: As I got it, your have to solve the problem of an "connection pool".
and a connection pool is an implementation of an "pooling pattern".
The difference, to the pattern (what I see) is, that in your implementation the user of the session knows something about the mangling with the connection and the pooling-stuff.
For me a more "pattern way" seems, if the user orders a session from the session-pool and give it back to it. So the pooling system knows if there are connections needed, and the creation/destroy-mechanism is transparent to the user.
The user gets the "connection" because he has a session.

Session creation doesn't require to work with the factory.

That maybe true, but the lifecycle of the session is vital to the lifecycle of the connection. So I would give the responsibility to create/destroy to the pool and not to the using objects.


text:
Q: Code skips formatting individual cells from text to numbers I am getting sensor data, that is stored in an Excel Worksheet. By some reason, the manufacturer of said sensor exports the measurement results as a text instead of a number.
Of course this can be changed manually. But due to the size and frequency of new sheets, I have decided to program a little Add-In that executes the following Makro:
Sub ConvertTextToNumber(ByVal control As IRibbonControl)
    With Range("=D5:G10000")
        .NumberFormat = "General"
        .Value = .Value
    End With

    With Range("=K5:L10000")
        .NumberFormat = "General"
        .Value = .Value
    End With
End Sub

In principle this works perfectly. Upon pressing a Button in the Ribbon bar, each number inside those ranges converts from text to number format. However, some cells are just immune to this. They cant get reformatted manually aswell. Ive tried numerous things, but ive reached the the end of my excel capabilities. I hope somebody can help with this problem.
Heres a picture showing an example of the problem. The green marked cells are still formatted as text.

A: Looks like Excel does not convert strings to numbers when using .Value = .Value so you need to explicitly convert them using CDec() into decimals (if the value is numeric).
Option Explicit

Public Sub Example()

    With [A1:A2] 'Range("D5:G10000")
        Dim ValueArr() As Variant
        ValueArr = .Value2   ' read values into array for fast processing

        ' Loop through 2 dimensional array
        Dim iRow As Long
        For iRow = LBound(ValueArr, 1) To UBound(ValueArr, 1)
            Dim iCol As Long
            For iCol = LBound(ValueArr, 2) To UBound(ValueArr, 2)

                ' convert strings to decimals if value is numeric
                If IsNumeric(ValueArr(iRow, iCol)) Then
                    ValueArr(iRow, iCol) = CDec(ValueArr(iRow, iCol))
                End If

            Next iCol
        Next iRow

        ' set numberformat and write array back to cells
        .NumberFormat = "General"
        .Value2 = ValueArr
    End With

End Sub

A: For all that have a similar problem: This was my final version of @Pᴇʜ
's answer that worked in the end. Thanks and credits!
Option Explicit

Public Sub ConvertTextToNumber(ByVal control As IRibbonControl)

    With [D5:G10000] 'Range("D5:G10000")
        Dim ValueArr() As Variant
        ValueArr = .Value2   ' read values into array for fast processing

        ' Loop through 2 dimensional array
        Dim iRow As Long
        For iRow = LBound(ValueArr, 1) To UBound(ValueArr, 1)
            Dim iCol As Long
            For iCol = LBound(ValueArr, 2) To UBound(ValueArr, 2)

                ValueArr(iRow, iCol) = Replace((ValueArr(iRow, iCol)), ",", Application.DecimalSeparator)
                ValueArr(iRow, iCol) = Replace((ValueArr(iRow, iCol)), ".", Application.ThousandsSeparator)

                ' convert strings to decimals if value is numeric
                If IsNumeric(ValueArr(iRow, iCol)) Then
                    ValueArr(iRow, iCol) = CDec(ValueArr(iRow, iCol))
                End If

            Next iCol
        Next iRow

        ' set numberformat and write array back to cells
        .NumberFormat = "General"
        .Value2 = ValueArr
    End With

    With [K5:L10000] 'Range("K5:L10000")
        Dim secondValueArr() As Variant
        secondValueArr = .Value2   ' read values into array for fast processing

        ' Loop through 2 dimensional array
        Dim secondiRow As Long
        For secondiRow = LBound(secondValueArr, 1) To UBound(secondValueArr, 1)
            Dim secondiCol As Long
            For secondiCol = LBound(secondValueArr, 2) To UBound(secondValueArr, 2)

                secondValueArr(secondiRow, secondiCol) = Replace((secondValueArr(secondiRow, secondiCol)), ",", Application.DecimalSeparator)
                secondValueArr(secondiRow, secondiCol) = Replace((secondValueArr(secondiRow, secondiCol)), ".", Application.ThousandsSeparator)

                ' convert strings to decimals if value is numeric
                If IsNumeric(secondValueArr(secondiRow, secondiCol)) Then
                    secondValueArr(secondiRow, secondiCol) = CDec(secondValueArr(secondiRow, secondiCol))
                End If

            Next secondiCol
        Next secondiRow

        ' set numberformat and write array back to cells
        .NumberFormat = "General"
        .Value2 = secondValueArr
    End With

End Sub

Note: Might have been unnessecary to do a second loop and rename every variable, but im new to VBA and this just worked!


text:
Q: PHP array from function passed onto array on new sheet I am trying to pass on an array from a function on one sheet into a new array on another php sheet.
Here's what i have:
The function is:
//the arr.php file

<?php

function search($var){
$var;

$a=array();
$a[0]=$var+1;
$a[1]=$var+2;
$a[2]=$var+3;
$a[3]=$var+4;
return $a;
}
?>

The second sheet is:
<?php

include ('arr.php');
$n=4;

for($i=0;$i<$n;$i++)
{

$temp=search(3);

$thearrayfromarr[$i]=$temp;//doesn't work
print_r($thearrayfromarr[$i]);//doesn't work
}

?>

I want the second sheet to have an array variable which i can echo that will output
the $a array data from the search function.
So that, for example, when i type
echo thearrayfromarr[0]; // It will have the value of $a[0] echo'd to me

A: Your function isn't returning anything:
function search($var) {
    $a=array();
    $a[0]=$var+1;
    $a[1]=$var+2;
    $a[2]=$var+3;
    $a[3]=$var+4;
    return $a; // Need this
}

A: Your search() function isn't returning $a. Here's a cleaned up version that works:
<?php
//the arr.php file

function search($var){
    $a = array();

    for($n=1; $n<=4; $n++) {
        $a[] = $var + $n;
    }

    return $a;
}
?>

A: You can simply return this array from the function:
return $a;

If you already return something else, you should declare $a as reference argument:
function search($var, &$a) {
  $a[0]=$var+1;
  $a[1]=$var+2;
  $a[2]=$var+3;
  $a[3]=$var+4;
  return "something";
}

$a = array();
$temp = search(3, $a);
// $a now has new value

A: The array you define inside the function is not accesible from outside. You need to return the array in order to use it.
Returning the array
function search($var){
$var;

$a=array();
$a[0]=$var+1;
$a[1]=$var+2;
$a[2]=$var+3;
$a[3]=$var+4;
return $a;
}

Then you use it like this:
include ('arr.php');
$n=4;

for($i=0;$i<$n;$i++)
{

$temp=search(3);

$thearrayfromarr[$i] = $temp;
print_r($thearrayfromarr[$i]);
}

In this case, if you do: $thearrayfromarr[0] should have [1,2,3,4] since you're returning an array, not a value.
This is particularly important since you're hoping for something else according to this line:
echo thearrayfromarr[0]; // It will have the value of $a[0] echo'd to me

To answer the question
How do I make $thearrayfromarr have the value of search(3)?
You don't need the for loop for that, you can just do:
include ('arr.php');

$thearrayfromarr = search(3);
print_r($thearrayfromarr); //should return [4,5,6,7]


text:
Q: Local DNS server (bind) and the router DHCP I just set up an internal http server for internal use (I set up Redmine), in a small network (30 or so PCs).
I set up the http server on a virtual box ubuntu, that runs also the DNS server (bind).
In the DNS lookup I added the Redmine server name (redmine.engserver <-> 192.168.1.14) and as forwarders the outside ISP DNS IP adresses.
I am using a small wi-fi router (ASUS RT-N66U) as DHCP (and as gateway). In the DHCP config page I set up as DNS the ubuntu server IP (it is fixed 192.168.1.14).
Now when I connect a new PC to the network, the DHCP router issues its new IP and as DNS servers it issues: primary: 192.168.1.14 (ubuntu machine) and seconary 192.168.1.1 (the router itself).

ipconfig /all
  Default Gateway . . . . . . . . . : 192.168.1.1
  DHCP Server . . . . . . . . . . . : 192.168.1.1
  DHCPv6 IAID . . . . . . . . . . . : 248539109
  DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-17-15-AA-3F-D0-67-E5-49-A7-EF

DNS Servers . . . . . . . . . . . : 192.168.1.14
                                    192.168.1.1
NetBIOS over Tcpip. . . . . . . . : Enabled
Before changing the DHCP setting on the router, I would always get only one DNS server: 192.168.1.1 (which uses probably DNS forwarding to external public DNS services).
The problem is this:
If in my browser I type www.google.com, it works all the time.
If in the browser I type http://redmine.engserver/ it works most of the time, but sometimes it ends up with a yahoo page search or something else. In the DNS cache it shows as (Server not found). ipconfig /displaydns
I looked with wireshark and it seems like sometimes the client PC interrogates the secondary DNS (192.168.1.1) instead of the first 192.168.1.14.
Obviously this one is a public domain and it does not have the redmine.engserver entry.
What is wrong in this configuration?
Is it even legitimate to have 2 DNS (one internal and one forwarded by the router) which are inconsistent?
Is there another way to have a local name service in a small office network?
Why is the router DHCP issuing itself as DNS?

A: You've already figured this out.  Half of your DNS requests go to the router instead of your internal DNS server (which cannot resolve 'redmine' internally.)  Your router should only assign 192.168.1.14 as a DNS server in DHCP.  In a network of your size, you can probably get away with only a single DNS server.  (This should be an option in the configuration.)

Is it even legitimate to have 2 DNS (one internal and one forwarded by the router) which are inconsistent?

No, it's very bad practice for the reasons you are experiencing.

Why is the router DHCP issuing itself as DNS?

Default settings for DHCP on any router will do this.  I suppose it could be some complete utter crap of a device that doesn't allow you to disable it.  If so, toss it in the trash at once and replace it with something that gives you control of your network.

A: FYI- I am seeing the exact same issue on my ASUS WiFi router.  I have an Asus RT-N16.  I also configured the dhcp server to give clients a different DNS server.  However, this asus insists on also giving clients the router's 192.168.1.1 address.  This is bad for the reasons you mentioned.
Is there any way to use dhcp on the router, but not its DNS?  I'm wondering if it might be better to just re-flash the router with dd-wrt.

A: If you have DNS on the ubuntu box, you can also remove the DNS entry from the router's DHCP (so it gives only the router itself as DNS to the client) and add the ubunto as primary DNS server and a fallback as secondary DNS server.


text:
Q: How to make regular expression "prefer" something? function getSrc($content) {
    $pattern = '<(?:content|src)="((?:https?://\d+\.media\.tumblr\.com)/(?:\w+)/(?:tumblr_[^_]+_(?:1280|500|400|250)\.(?:png|jpg|gif)))">i';
    preg_match($pattern, $content, $matches);

    return $matches[1];
}

in case content in this order:
...500.jpg...
...1280.jpg...
...400.jpg...

the $matches[1] would be 500, since 500 show up before 1280, but I would like 1280 when there has one.
Is it possible making the regular expression prefer to return bigger number?
finally, I change my code for life saving:
function getSrc($content) {
    $pattern = '<(?:content|src)="((?:https?://\d+\.media\.tumblr\.com)/(?:\w+)/(?:tumblr_[^_]+_(1280|500|400|250)\.(?:png|jpg|gif)))">i';
    preg_match_all($pattern, $content, $matches);
    array_multisort($matches[2], SORT_DESC, $matches[1]);

    return $matches[1][0];
}

A: Yes, but with a serious caveat: it's much slower because it rescans the string for each option:
$pattern = '<^(.*(1280)|.*(500)|.*(400)|.*(250))">';

Basically, ^ anchors the regex to the left, then each option is matched in full. Obviously, this is very inefficient for long strings, but it does the trick.
Also, I apologize if it's not the function of them, but I'm assuming the regex is meant to match something like 1280", but if the " was not intended, it seems this would be preferable:
$pattern = '<^(.*(1280)|.*(500)|.*(400)|.*(250))>';

When extracting, use groups 2 through 5. Alternatively, remove the excess group parenthesis, and do a second match to '<(1280|500|400|250)>' to extract the value.
Note: the options in this answer don't use the case-insensitive tag, but you can always include if it's needed due to some other part of your regex.


text:
Q: Unit test for Python AWS Lambda: mock function before module is imported I'm trying to write unit tests for my aws lambda function written in python 3.9. I tried different things to mock the get_object function that makes calls to the S3. I wanted to focus only on the calculate method, to verify if I'm getting correct results of an calculation.
When I try to run the following approach I'm getting credential errors about boto3
python -m unittest tests/app-test.py
...
botocore.exceptions.NoCredentialsError: Unable to locate credentials

Is there a way to import the calculate method from app.py and mock call to the get_object fn?
directory:
functions:
- __init__.py
- app.py
tests:
- __init__.py
- app-test.py

lambda function app.py:
import json
import boto3

def get_object():
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket='mybucket', Key='object.json')
    content = response['Body'].read().decode('utf-8')
    return json.loads(content)

stops = get_object()

def lambda_handler(event, context):
    params = event['queryStringParameters']
    a = int(params['a'])
    b = int(params['b'])

    result = calculate(a, b)
    return {
        'statusCode': 200,
        'body': json.dumps(result)
    }

def calculate(a, b):
    return a + b

unit test app-test.py:
import unittest
from unittest import mock

with mock.patch('functions.app.get_object', return_value={}):
    from functions.app import calculate

class TestCalculation(unittest.TestCase):
   def test_should_return_correct_calculation(self):
     # when
     result = calculate(1, 2)

     # then
     self.assertEqual(3, result)

A: I was able to fix the issue. The biggest obstacle was to mock the boto3 in the app.py. I did this, by mocking the whole boto3 module before it's imported. Here's the code of app-test.py
import sys
from io import BytesIO
from json import dumps
from unittest import TestCase, main
from unittest.mock import Mock
from botocore.stub import Stubber
from botocore.session import get_session
from botocore.response import StreamingBody

# prepare mocks for boto3
stubbed_client = get_session().create_client('s3')
stubber = Stubber(stubbed_client)

# mock response from S3
body_encoded = dumps({'name': 'hello world'}).encode()
body = StreamingBody(BytesIO(body_encoded), len(body_encoded))
stubbed.add_response('get_object', {'Body': body})

stubber.activate()

# add mocks to the real module
sys.modules['boto3'] = Mock()
sys.modules['boto3'].client = Mock(return_value=stubbed_client)

# Import the module that will be tested
# boto3 should be mocked in the app.py
from functions.app import calculate

class TestCalculation(TestCase):
   def test_should_return_correct_calculation(self):
     # when
     result = calculate(1, 2)

     # then
     self.assertEqual(3, result)


text:
Q: Removing Objects from UITableView So I've seen similar topics but I don't quite understand why I am crashing still....
I am reading entries into an array called "entries."  After a while I want to add new entries and then delete the old ones.
So I'm essentially adding stuff to 'entries" and then wanting to delete some old entries.  I then run the below method and dies out when it starts editing the view.  The error is posted below the code block.
Thanks for the help!
-(void) removeOldEntries:  (int) numOfEntries
{

    NSMutableArray *deleteIndexPaths = [[NSMutableArray alloc] init] ;

 //  Remove the first number of entries in the table view.  This number is specified by the numOfEntries
 for (int i = numOfEntries - 1; i >= 0; i = i -1 )
 {
     [entries removeObjectAtIndex:i];
 }

//  Build deleteIndexPaths
for (int i = numOfEntries - 1; i >= 0; i = i - 1)
{
    //  Add objects to our index pathes array (of things we need to delete) and then remove the objects from feeds array
    [deleteIndexPaths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}

//  Start the editing of the TableView
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];
//  End the editing of the table view
[deleteIndexPaths removeAllObjects];
[deleteIndexPaths release];
}

Error message:
 *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UITableView.m:976
2011-12-27 22:43:04.490 v1.0[999:6003] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (8) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00e3dbe9 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x00f925c2 objc_exception_throw + 47
    2   CoreFoundation                      0x00df6628 +[NSException raise:format:arguments:] + 136
    3   Foundation                          0x000d847b -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
    4   UIKit                               0x0035aa0f -[UITableView(_UITableViewPrivate) _endCellAnimationsWithContext:] + 8424
    5   UIKit                               0x0034a433 -[UITableView endUpdates] + 42
    6   v1.0                                0x000050e6 -[NewsTableViewController removeOldArticles:] + 408
    7   v1.0                                0x00004d16 -[NewsTableViewController pullAndParseData] + 696
    8   CoreFoundation                      0x00dae67d __invoking___ + 29
    9   CoreFoundation                      0x00dae551 -[NSInvocation invoke] + 145
    10  Foundation                          0x000ff555 -[NSInvocationOperation main] + 51
    11  Foundation                          0x0006dbd2 -[__NSOperationInternal start] + 747
    12  Foundation                          0x0006d826 ____startOperations_block_invoke_2 + 106
    13  libSystem.B.dylib                   0x96653a24 _dispatch_call_block_and_release + 16
    14  libSystem.B.dylib                   0x96645cf2 _dispatch_worker_thread2 + 228
    15  libSystem.B.dylib                   0x96645781 _pthread_wqthread + 390
    16  libSystem.B.dylib                   0x966455c6 start_wqthread + 30
)
terminate called after throwing an instance of 'NSException'

A: Use [_tableView reloadData]. This will simplify your life.
By the way, the exception you are getting is indicating that your array is not containing what you think it should. Trying NSLogging your array.

A: You are making this needlessly complicated. There is some inconsistency in your deletion which is why there is an error. Make sure in
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //return for section 0
    return [entries count];
}

And change your removeOldEntries: to
-(void) removeOldEntries:  (int) numOfEntries
{

[entries removeObjectsInRange:NSMakeRange(0, numOfEntries-1)];
[self.tableView reloadData];
}


text:
Q: Taking Screenshot of Excel Find and Replace results along with clock I am using sendkeys to manipulate the options in Find and Replace. However, when it comes to taking screenshots, it captures the screenshot without the results. Most of my searches (99%) return no result. I just have to take a screenshot of the entire active screen (I use a dual monitor) and save the file as a jpg or pdf.
The code I have so far is
Sub Seachpdfer()
 Dim searchquery As Range
 Dim mystring As String
 Dim mypic As Shape

 Set searchquery = Worksheets("Query").Range("AA2:AA10001")

 For Each cell In searchquery

    mystring = cell.Value

    If cell.Value = "" Then
        Exit For
    End If

  Worksheets("Restricted List").Select
  Worksheets("Restricted List").Range("A1").Activate
  Worksheets("Restricted List").Range("I1").Activate

  Application.CommandBars("Edit").Controls("Find...").Execute

  Application.SendKeys ("%n" & mystring)
  Application.SendKeys ("{TAB}{TAB}")
  Application.SendKeys ("Sheet")
  Application.SendKeys ("{ENTER}")
  'Application.SendKeys ("{TAB}{TAB}{TAB}{TAB}{TAB}{TAB}")
  Application.SendKeys ("{TAB}{TAB}")
  Application.SendKeys "%i", True  ' This clicks the Find button on the Find and Replace dialog

' This is where it all breaks. I tried using doevents and tried using application wait. But the screenshot I get does not show
'The search result We could not find what....."

  Application.SendKeys "({1068})", True
  DoEvents
  ThisWorkbook.Worksheets("Staging").Activate
  ActiveSheet.Paste
  sFileName = ThisWorkbook.Path & "\" & mystring & ".jpg"

  For Each mypic In ActiveSheet.Shapes

        mypic.Select

       Call PictureExport ' This function converts it to a chart and prints out the pdf

   Next

 Next
End Sub

Any help will be much appreciated. Thank you.


text:
Q: Server or Desktop for web development I apologize ahead of time if this is a repeat question. I'm a linux noob and want to use it for website development. I installed the Server version and got a working LAMP installed via the command line. However, I don't see any web browser. How will I be able to view/test my site as I'm developing if I can't install a major browser, e.g Firefox, Chrome, IE, etc. Is the solution to use Ubuntu Desktop instead? thanks!

A: Ubuntu Server is what it is advertised as - a Server. While you can develop using command line tools, it will be a major pain in the @$$. With that, you can install the Ubuntu Desktop version and install the LAMP or LEMP stack (whichever you prefer) after.
Basically, you have two options.

*

*If you have already installed Ubuntu Server, you can just add in the Ubuntu Desktop package by issuing the command sudo apt-get install ubuntu-desktop.

*If you have Ubuntu Desktop installed, issue the following command on the terminal to install the LAMP Stack : sudo apt-get install tasksel && sudo tasksel. Once tasksel starts, you can install the LAMP Stack.
I would however recommend you to try out LEMP (NGINX instead of Apache2). If you would like to do that, follow the instructions on this site.


text:
Q: Can I do an ANOVA while controlling for a categorical variable (an ANCOVA except the covariate is categorical) I'm looking at nesting differences between 3 species of fish. These fish nest in colonies (all 3 species intermix in the colonies), and measurements were taken at several different colonies throughout the lake. I am wanting to see how continuous variables such as nest depth vary between the 3 species. Depth also varies between colony, but I do not care about this difference. Is there a way I can investigate differences in nest depth between species, while controlling for the underlying differences in nest depth between colonies? Thanks!

A: ANOVA, ANCOVA and so on are basically tests based on regression models. So, if you can specify and fit a suitable a regression model, you can get what you describe there. In this case, I'd guess we are talking about a linear regression for depth (or perhaps log(depth), since depth cannot possible be negative, right? Although that then also implies relative depth difference such as a 10% deeper instead of absolute differences like 10 cm deeper), in which you allow a completely different depth for each colony (i.e. it's a categorical factor, that we would use dummy coded on) and then also for species relative to the depth of the colony.
In R syntax that could then look like lm( depth ~ 0 + factor(colony) + factor(species)) or lm( log_depth ~ 0 + factor(colony) + factor(species)). The syntax I used assumes you did not already declare in your dataframe or tibble that colony and species are categorical factors rather than numerical data, in which case you could omit the factor() around the variables. 0+ just means I don't want an intercept, but you could also get any comparisons you want if you had an intercept. Just about any other statistical software should be able to fit such a model, too. You'd be asking how much each species is off from the depth of the colony, you could argue that you're assuming that it's always to the same extent across all colonies or at least that you're asking for an answer as if that were the case (and it made sense to just average while controlling for the colony depth).
You can then look at the coefficients for the different species and/or ask for comparisons (each software will have its own ways of specifying what you want e.g. with the emmeans R package, with the LSMEANS statement in SAS etc.).


text:
Q: Array reference versus scalar reference I have this code segment to put together a hash of parameters which I will pass to a function. The hash value containing the IP address is supposed to be an array reference, but the function I'm passing my parameters to thinks it's a scalar reference.
My code is:
my $paramList = "ldap_ip_addresses=['192.168.1.100']|ldap_port=389|ldap_protocol=ldap";
my @paramTuples = split(/\|/, $paramList);

my %nasProps;
foreach my $paramTuple (@paramTuples) {
    my($key, $val) = split(/=/, $paramTuple, 2);

    # SetProperties can also take hashes or arrays
    my $eval_val = eval $val;
    if (ref($eval_val) =~ /ARRAY/) {
        $val = \$eval_val;
    }
    $nasProps{$key} = $val;
}

From the debugger, my parameter hash looks like this:
DB<18> x \%nasProps
0  HASH(0x303f8f0)
'ldap_authentication_type' => 'anonymous'
'ldap_ip_addresses' => REF(0x303fa70)
   -> ARRAY(0x8284eb8)
        0  '192.168.1.100'
'ldap_port' => 389
'ldap_protocol' => 'ldap'

It looks like a reference to an array so I'm not sure where I'm going wrong.

A: Since $eval_val is already a reference to an array, there is no need to make a reference to the reference.  Change:
$val = \$eval_val;

to:
$val = $eval_val;

A: You are unnecessarily taking the reference to a reference with
$val = \$eval_val;

You have established on the previous line that $eval_val is a reference to an array, so you can use it as it is without taking a reference to it again.
In addition, you should ignore the result of ref $eval_val except to check that it is true — i.e. $eval_val is a reference of some sort.
Your code should look more like this. You need to fall back to the original $val value only if eval returns undef, usually meaning that the string wasn't compilable code.
Note also that you should reserve capital letters for global Perl variables, such as package names. Lexical variable identifiers should contain only lower-case letters, decimal digits and underscores.
use strict;
use warnings;

my $param_list   = "ldap_ip_addresses=['192.168.1.100']|ldap_port=389|ldap_protocol=ldap";
my @param_tuples = split /\|/, $param_list;

my %nas_props;
for my $param_tuple (@param_tuples) {
    my ($key, $val) = split /=/, $param_tuple, 2;
    $nas_props{$key} = eval($val) // $val;
}

use Data::Dump;
dd \%nas_props;

output
{
  ldap_ip_addresses => ["192.168.1.100"],
  ldap_port         => 389,
  ldap_protocol     => "ldap",
}

A: Here is a short alternative in functional style:
my %nasProps =
     map /\[/ ? eval : $_,
     split /[|=]/, $paramList;

However, it only works if you can guarantee that = is not included in any parameter values.


text:
Q: Calling a function within a for loop, asynch problem I am trying to insert a row into my FILE table, but when I attempt this the order in which things are done isn't what I want it to be. I know that JS is asynchronous but, I'm not sure how that affects how I should work within a loop.
Some background, sharedLib.serverCreateCalendar(file) just takes a .ics file and converts its content to a JSON so i can get the info out of it
I don't have much experience with JS or SQL so I don't have any idea what I should do to fix this.
for (var i = 0; i < files; i++) {
  cals = sharedLib.serverCreateCalendar(file); // get the cal info as a JSON

  var obj, fileN, version, prodID, evtNum; //variables for parsing the JSON and getting the values
  var obj = JSON.parse(cals); //parse the calendar JSON

  //Assign the values i want
  fileN = files[j];
  version = obj.version;
  prodID = obj.prodID;
  evtNum = obj.numEvents;

  //SQL to insert into the FILE table
  var calInsert = ("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");"); //This is the SQL to insert into the FILE table with its required info
  console.log(calInsert);

  //Send the SQL query to add a file
  connection.query(calInsert, function(err, result) {
    if (err) { //error inserting into the DB
      console.log("Calendar insert error");
      res.send("Error");
    } else { //if placing the calendar is good then add the events
      console.log("Added the calendar!");
    }
  });

}

Ideally this would output
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!

("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!

("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!

and so on until i'm done looping but, it outputs this instead
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");");
Added the calendar!
Added the calendar!
Added the calendar!

A: In your example the files are being inserted but each loop iteration is not waiting for the file to be inserted. If you want your console logs to look like you describe you need to insert the next file after the call back. You can achieve this by removing the for loop altogether:
var files = []; // Get an array of files some how

function insertFiles(theFiles) {
    // Handle end condition
    if (theFiles === undefined || theFiles.length == 0) {
        return;
    }
    var cals = sharedLib.serverCreateCalendar(file); // get the cal info as a JSON
    var obj = JSON.parse(cals); //parse the calendar JSON
    var fileN = theFiles.shift();   // Get the first file and remove from array
    var version = obj.version;
    var prodID = obj.prodID;
    var evtNum = obj.numEvents;

    //SQL to insert into the FILE table
    var calInsert = ("INSERT INTO FILE (file_Name, version, prod_id) VALUES('" + fileN + "'," + version + ",'" + prodID + "'" + ");"); //This is the SQL to insert into the FILE table with its required info
    console.log(calInsert);

    //Send the SQL query to add a file
    connection.query(calInsert, function(err, result) {
        if (err) { //error inserting into the DB
            console.log("Calendar insert error");
            res.send("Error");
        } else { //if placing the calendar is good then add the events
            console.log("Added the calendar!");
            insertFiles(theFiles);
        }
    });
}

insertFiles(files);

But, of course, as has been pointed out in the comments there may be other issues with SQL insertion command written the way it is.


text:
Q: How to Implement a user and user account with data for iOS I'm currently making an app for iOS, I have successfully integrated the facebook SDK and i'm able to login with facebook. In my app, people can post, like, and comment on other posts. Now I have no idea how to do this or even how it will work. Please if someone could concisely explain to me how it could be done.
For Example how does Instagram work when you log in with facebook, does it have a database and just use a facebook user as an id on that database to get data or what ? Thanks a millionnn !
P.s I know this is quite a broad topic but no matter how small you can explain, it would be gladly appreciated.

A: Instagram and app like that have there on database and first time we login there with facebook a user will be created in their db (there will be userid and all like a user registered normally) and the posting like comment and all are managed with that user in there db.


text:
Q: Describe the action of r^-1 on the square and express r^-1 as a word using r only It says let r be the element of R4 that rotates the square by 90 degrees clockwise
What I did was make a square and I turned it 90 degrees. So would the inverse of the 90 degree square be the counter
clockwise

A: Yes, the inverse of a 90 degree rotation clockwise is a 90 degree rotation counterclockwise. The question you are being asked however is how you express that in terms of $r$ i.e. how do you express a 90 degree rotation counterclockwise in terms of 90 degree rotations clockwise.
A hint is to consider what happens if you take powers of $r$, i.e. what happens if you rotate 90 degrees clockwise multiple times.


text:
Q: r as.Date returns previous day as.Date(date1) is incorrectly returning the previous day.
I suspect it has got to do with time zones, but I am still learning the very basics of R so I have little chance of solving it on my own.
The code I use to produce this is:
> a <- (capital_paid_summary_per_loan$Arrears_Date[1])
> a
[1] "2015-08-31 SAST"
> as.Date(a)
[1] "2015-08-30"
>

As you can see, the date starts off to be "2015-08-31" but as.Date() changes it to one day prior.
Any advice is welcome

A: If
date <- "2015-08-31 SAST"

You could use:
as.Date("2015-08-31 SAST",tz='SAST')

Which specifies the timezone as SAST, or you could use:
as.Date(gsub(' SAST','',date))

Which will remove the timezone from part of the string and then convert to date.