text:
Q: PHP regex, incorrect escaping of html causing problem I'm trying to use (.+?) to isolate the words "I. NEED. ISOLATION" in the source below:
Label:

      I. NEED. ISOLATION

using (.+?), I could do this:
$regex = '/stuff before(.+?)stuff after/';

and for this html, that would be:
$regex = '/Label:

      (.+?)   	/';

but it's choking up on it because of incorrect escaping. I'm not great in PHP. Can someone please advise which characters I should also escape based on html that looks like this?
Label:

      I. NEED. ISOLATION

Note that I'm not trying to design a regex pattern. I already have the pattern nailed down with (.+?), just need to know how to correctly escape the html so that php doesn't choke up on it.

A: See this previous StackOverflow question.
That said, the escaping issue is due to the / characters within, which are confusing the regex parser since you're using /es already to delimit the regex.

A: First of all, you should really not use regular expressions to try to "parse" HTML -- which is not quite regular.
Going with something like DOMDocument::loadHTML and some XPath query is generally a much better solution.

But, if you really want to go with a regex (and it seems you do, judging from your comments to other answers), I suppose you should not use / as regex delimiter : there are too many slashed in HTML already -- it'll be an escaping hell, as you already noticed.
For instance, you could use a # as regex delimiter :
$str = <<<STR
Label:

      I. NEED. ISOLATION
STR;
$regex = '#Label:

      (.+?)   	#';
if (preg_match($regex, $str, $m)) {
  var_dump($m[1]);
}

Will get you :
string 'I. NEED. ISOLATION' (length=18)

Note the only thing I changed compared to your proposed code is the regex delimiter ;-)

And, using a character that's not present in the HTML string, I don't have anything to escape -- especially, I don't have to escape all the /s -- which means the regex is far more easy to both write, read, and understand.

A: If you're using PCRE regular expressions, you need to escape the delimiters inside the regular expression (in your case the /):
'/Label:<\/strong><\/font><\/td>

  (.+?)  <\/font> <\/td>/'

But probably more important: Regular expressions are not suitable for parsing HTML. Better use a proper HTML parser like the one provided by DOMDocument and query it with DOMXPath.

A: $str=<<<EOF
Label:

      I. NEED. ISOLATION
EOF;

$s = explode("",$str);
foreach($s as $k=>$v){
    if(strpos($v,'')){
        $t=explode('',$v);
        print trim($t[1])."\n";
    }
}

output
$ php test.php
I. NEED. ISOLATION

A: There is a funciton that does that for you. It's named preg_quote http://pl2.php.net/preg_quote
$regex = '/'.preg_quote('Label:

  ').'(.+?)'.preg_quote('   	).'/';

You should also be careful with case sensitivity and line breaks. I often tend to add flags to my regexps to deal with it so they look like /(.+?)/is

A: As a matter of fact, there's nothing in that string that has special meaning in a regex (except the (.+?), of course).  The only reason the / is causing a problem is because you're using it as the regex delimiter.  You just need to choose a different delimiter, like ~ for example:
$regex = '~Label:

      (.+?)   	~';


text:
Q: console.time() in IE8 Developer Tools Is there an equivalent to
console.time('');
console.timeEnd('');

in IE8 Developer Tools?

A: There isn't, but you can define it easily with JavaScript:
// console.time implementation for IE
if(window.console && typeof(window.console.time) == "undefined") {
    console.time = function(name, reset){
        if(!name) { return; }
        var time = new Date().getTime();
        if(!console.timeCounters) { console.timeCounters = {}; }
        var key = "KEY" + name.toString();
        if(!reset && console.timeCounters[key]) { return; }
            console.timeCounters[key] = time;
        };

    console.timeEnd = function(name){
        var time = new Date().getTime();
        if(!console.timeCounters) { return; }
        var key = "KEY" + name.toString();
        var timeCounter = console.timeCounters[key];
        var diff;
        if(timeCounter) {
            diff = time - timeCounter;
            var label = name + ": " + diff + "ms";
            console.info(label);
            delete console.timeCounters[key];
        }
        return diff;
    };
}

Just place it in your JS file before you want to use console.time() and console.timeEnd().
It is not my code, I actually copied it from Firebug core.

A: If you want to use Firebug in IE, there is a version called Firebug Lite, which can be used in any browser as a 'Bookmarklet'.
http://getfirebug.com/firebuglite
It isn't as functional as the real thing, but it can do a lot so it may be worth a try.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Crud Operations as Callback Function I wonder how to write CRUD operations as callbacks so that the Seperation of Concerns is respected.
As an example, I coded the operation that can return all users:
UserService.js
function getUsers(callback) {

  User.find(function(err, users) {

    if (err) {
      console.log("Fehler bei Suche: " + err)
      return callback(err, null)
    }
    console.log("Alles gut gelaufen.");
    return callback(null, users);
  })
}

UserRoute.js
router.get('/publicUser', function(req, res, next) {

  userService.getUsers(function(err, result) {
    console.log("Resultat: " + result)
    if (result) {
      res.send(Object.values(result))
    } else {
      res.send("Es gab Probleme.")
    }
  })

})

A corresponding CRUD function, with no callback, that returns exactly one user looks like this to me.
Userservice.js
function getByUserId(req, res, next) {

  let userIDD = req.body.userID;
  User.findOne({
    userID: userIDD
  }, function(err, result) {
    if (err) {
      console.log("Fehler bei Suche: " + err)
    } else {

      console.log("Alles gut gelaufen.");
      res.send(result)
    }
  })
}

UserRoute.js
router.post('/publicUser/getByUserID', userService.getByUserId)

Now what exactly does the same function look like with callback ?

A: Generally arrow functions are used for callback so that the Seperation of Concerns is respected.
Example:
In UserRoute.js
router.get('/publicUser', (req, res, next) => {
  userService.getUsers( (err, result) => {
    console.log("Resultat: " + result)
    if (result) {
      res.send(Object.values(result))
    } else {
      res.send("Es gab Probleme.")
    }
  })

})

Here you can see there is no need for writing function for every callback and arrow function also helps in seperation
This is my first time answering any questions on stackoverflow , i hope solution understood you :)


text:
Q: Apache Camel: Producer template does not add to SEDA endpoint I am not sure what the problem is with my small application, if it resides on the RouteBuilder or within the ProducerTemplate
Either way, my "Test message" is not logged when running this application.
What may be going wrong here?
public static void main(String[] args) {

        Main main = new Main();
        main.addRouteBuilder(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:myqueue").log(LoggingLevel.INFO, "${in.body").end();
            }
        });

        ProducerTemplate producerTemplate = main.getOrCreateCamelContext().createProducerTemplate();
        producerTemplate.setDefaultEndpointUri("seda:myqueue");
        producerTemplate.sendBody("Test message");
    }

A: It doesn't look like you are creating and starting the context which is probably why the message never reaches your route. Here is an example to get you started:
https://examples.javacodegeeks.com/enterprise-java/apache-camel/apache-camel-hello-world-example/
import org.apache.activemq.camel.component.ActiveMQComponent;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

public class CamelHelloWorldExample {
    public static void main(String[] args) throws Exception {
        CamelContext context = new DefaultCamelContext();
        try {
            context.addComponent("activemq", ActiveMQComponent.activeMQComponent("vm://localhost?broker.persistent=false"));
            context.addRoutes(new RouteBuilder() {
                @Override
                public void configure() throws Exception {
                    from("activemq:queue:test.queue")
                    .to("stream:out");
                }
            });
            ProducerTemplate template = context.createProducerTemplate();
            context.start();
            template.sendBody("activemq:test.queue", "Hello World");
            Thread.sleep(2000);
        } finally {
            context.stop();
        }
    }
}

Notice context.start() and context.stop();


text:
Q: H3 polyfill for country-scale polygons I am trying to generate a grid for a given (multi) polygon. I understand a grid as a collection of h3 indices within a (multi)polygon boundary.
Here is the code that I implemented so far:
 def generate_grid(region_bounds: gpd.GeoDataFrame) -> pd.DataFrame:
        """
        Generates H3 resolution 10 grid. It utilizes the h3.polyfill method.
        For more detail see https://geographicdata.science/book/data/h3_grid/build_sd_h3_grid.html

        Returns: a dataframe with the following columns:
            <index, h3_res_10>
        """
        logging.info("Start grid generation")
        start = time.time()
        resolution = 10
        grid = region_bounds.h3.polyfill(resolution)
        end = time.time()
        logging.info(f"grid generation took {end - start} sec")
        # convert polyfill result to df
        grid_df = pd.DataFrame.from_dict({"h3_res_10": grid.h3_polyfill[0]})
        logging.info(grid_df)
        return grid_df

The problem occurs when the region to process is big, like a country or state.
Is there any way to run the polyfill in parallel for multiple subregions? How can I efficiently split the region into subregions to run h3.polyfill in parallel?

A: Yes, polyfill (polygonToCells in v4) can be CPU/memory intensive for large regions at fine resolutions of H3. Res 10 is roughly a city block, so a large country will likely have millions of cells.
The best option at the moment is to split up the input into contiguous polygons. The resulting cells will not overlap if the input polygons do not overlap. In Python, you could try Shapely to split the polygon, simply taking vertical tranches with successive north-south lines as the splitters: shapely.ops.split
The resulting set of polygons can then be processed either serially or in parallel with much less memory pressure. CPU time is roughly the same or higher, but could be split across threads.


text:
Q: How can I search a key containing '&' or '"' in CouchDB VIEW When I query like the following in CouchDB:
curl -X GET "localhost:5984/content/_design/names/_view/by_name?key=%22xxx&xxx%22"

It returns:
{"error":"bad_request","reason":"invalid_json"}.

And when I remove the '&' from the key, then it is OK.
Could you please tell me how can I search a name containing '&' in VIEW? Or is the '&' forbidden in CouchDB keys?
Thanks.
Encoding for '&' works. But how to deal with '"'(%22)? As we all konw, we have to quote the value when querying in CouchDB.

A: You will have to encode the uri component. The encoding for & is %26.
curl supports --data-urlencode parameter to encode keys for you. So you can also try this
curl -G -v  http://localhost:5984/content/_design/names/_view/by_name --data-urlencode 'key="some key text & other key text"'


text:
Q: When to use UIApplication.keywindow and UIApplicationDelegate.window? I'm working on a somewhat new project (with Swift) and I just realized UIApplication.keywindow and UIApplicationDelegate.window are being used (apparently) like they are the same.
From this question I understand the are in fact NOT the same; but it's really not clear to me why or how they are different, when should each one be used.
Also the documentation here and here is rather cryptic in the meaning of each attribute, so I don't really understand if I can use one or the other, if I should one of both. In any case, any light on this mess would be great.  Thanks!


text:
Q: Recursively COPY files matching filename and preserve directory structure Assume I have the following dir structure:
languages
    -en-GB
      --page1.json
      --page2.json

    -fr-FR
      --page1.json
      --page2.json

Now let's assume I want to copy the folder structure, but only page1.json content:
I've tried this:
COPY ["languages/**/*page1.json", "./"]
Which results in the folders being copied, but no files.
What I want to end up with is
languages
    -en-GB
      --page1.json

    -fr-FR
      --page1.json

Copied into my image

A: I am not sure you can use wildcards to produce the filtered result you are looking for.
I believe there are at least two clean and clear ways to achieve this:
Option 1: Copy everything, and cleanup later:
FROM alpine
WORKDIR /languages
COPY languages .
RUN rm -r **/page2.json

Option 2: Add files you don't want into your .dockerignore
# .dockerignore
languages/**/page*.json
!languages/**/page1.json

Option 3: Copy all to a temporary directory, and copy what you need from inside the container using more flexible tools
FROM alpine
WORKDIR /languages
COPY languages /tmp/langs
RUN cd /tmp/langs ; find -name 'page1.json' -exec cp --parents {} /languages \;
CMD ls -lR /languages


text:
Q: Query blocked by spid no 21 (SQL Server 2014) Issue: I am running this query that inserts about 3,300,000,000 rows from table_A into table_B:
declare @i bigint, @j bigint, @page int

set @i = 1
set @j = 110000000
set @page = 0

while @page < 33
begin
    insert into table_B
        select column1, column2
        from table_A
        where id between (@i + @j * @page) and (@j + @j * @page)

    set @page = @page + 1
end

The query has been running for about 3 days 17 hours, and it's still running. After I checked sys.sysprocess, I found this query (spid = 108) was blocked by another spid = 21. I try to use dbcc inputbuffer (21) to check what's spid = 21 doing, but I can't find anything about this spid = 21.
Querying sys.sysprocesses:
select *
from sys.sysprocesses
where blocked != 0

Running dbcc inputbuffer (21):

Any help will be appreciated.


text:
Q: Python SQLite near "?": syntax error Another one of those questions. I'm trying to do:
self.table = 'table'
a = 'column'
b = 'value'

c.execute('INSERT INTO ? (?) VALUES (?)', (self.table, a, b))

But I'm getting
<class 'sqlite3.OperationalError'>:near "?": syntax error

At the same time,
c.execute('INSERT INTO {0} ({1}) VALUES ({2})'.format(self.table, a, b))

Works flawlessly, except for the security concerns.
I realize I'm not the first one to have this issue, but I have yet to find a solution that works for me.

A: Table names, column names cannot be parameterized. Try following instead.
self.table = 'table'
b = 'value'

c.execute('INSERT INTO {} ({}) VALUES (?)'.format(self.table, a), (b,))


text:
Q: Insert BoundField into DetailsView Basically I have a detailsview, dependent on what query it is I have certain BoundFields I'd like to show or hide.
Using visual basic, I know that I can use .visible = false. That does the trick, however, it sacrifices my alternating row style in the process.
Any ideas?
Thanks
By the way if you write it in C# I will probably understand.

A: What you need to do is create several asp:panel objects.  Inside each panel object, put a single DetailsView.  In your codebehind, you will want to show the panel that contains the proper DetailsView for your query, and hide the rest of the panels.


text:
Q: How to remove quotes from a PHP variable (PHP API) I made an API in PHP and un try to remove quotes of my PHP variables.
Here is the code for my API:
  for ($i = 0; $i < 48; $i += 1) {
        $hourly[$i] =
            array(
                "seeing" => $seeing[$i]),
                "transparency" => $transparency[$i],
                "time" => $timeforapi[$i]
            );
    }

And here is the return of my API:
"hourly": [
    {
        "seeing": "1.2",
        "transparency": "0.5",
        "time": 1672074000
    },

But as you can see there are quotes for seeing and transparency.
I try this to remove it but it doesn't take it away
  "seeing" => str_replace('"', "", $seeing[$i]),

A: The values of $seeing and $tranparency are strings. Convert them to numbers before putting them into the array.
for ($i = 0; $i < 48; $i += 1) {
    $hourly[$i] =
        array(
            "seeing" => floatval($seeing[$i])),
            "transparency" => floatval($transparency[$i]),
            "time" => $timeforapi[$i]
        );
}


text:
Q: Differential Equation Intuition - Wolfram Alpha Incorrect? Consider the differential equation
$$f'(x)=\frac{f(x)}{2x} - \sqrt{f(x)}. $$
Per Wolfram Alpha, its solution is
$$f(x)=\frac{1}{9}(4x^2-12cx^{5/4}+9c^2 x^{1/2}).$$
From the differential equation, we can see that when $x$ and $f(x)$ are large, the function has a negative slope. However, we see from the solution that when $x$ is large, so is $f(x)$, yet the function has a positive slope. What explains this apparent contradiction in intuition?
Here is an example with concrete values. Setting $c=1$, $f(20) = 125$. From the solution, $f$ slopes upwards at $x=20$. Yet according to the differential equation, $f'(20) = 125/40-125^{0.5} = -8$, which suggests $f$ slopes downwards. What explains this disconnect?
Here is an interactive Desmos graph showing these functions and calculations. As you can see, the derivative of $f$ as calculated by Desmos is markedly different from the slope given by the differential equation. Is there any chance Wolfram Alpha got this wrong? Or is there some other explanation for the seeming contradiction?
Any feedback or guidance would be greatly appreciated.

A: Ignoring the $f=0$ solution, we can rearrange the equation to see that
$$\frac{f'}{\sqrt{f}} = 2(\sqrt{f})' = \frac{1}{2x}\sqrt{f}-1$$
a linear equation in $\sqrt{f}$, which we can solve by integrating factor
$$\int\left(\frac{\sqrt{f(x)}}{x^{\frac{1}{4}}}\right)' = \int-\frac{1}{2x^{\frac{1}{4}}} \implies \sqrt{f(x)} = Cx^{\frac{1}{4}}-\frac{2}{3}x$$
However, at this stage, $C$ is not allowed to be any real number - it is dependent on the domain of the function. For positive $x$ we have that
$$Cx^{\frac{1}{4}}-\frac{2}{3}x\geq 0 \implies C \geq \frac{2}{3}x^{\frac{3}{4}}$$
Your choice of $C=1$ was invalid because extending the domain of the function to $20$ puts a lower bound on $C$ to be
$$C \geq \frac{2}{3}(20)^{\frac{3}{4}} \approx 6.3049$$
Alternatively, once $C$ is chosen, it provides an upper bound to the domain of the function, in which case $C=1$ puts the maximal extent of the interval of existence to be
$$0 < x \leq \left(\frac{3}{2}C\right)^{\frac{4}{3}} = \left(\frac{3}{2}\right)^{\frac{4}{3}} \approx 1.717$$
You cannot have arbitrarily large $x$.


text:
Q: Eclipse RCP: Right aligned search field in toolbar I would like to have a right aligned search field in the toolbar of an Eclipse RCP application. I already created the text field as ControlContribution and the respective search action in the ActionBarAdvisor class:
protected void fillCoolBar(ICoolBarManager coolBar) {
  IToolBarManager toolbar = new ToolBarManager(SWT.FLAT | SWT.RIGHT);
  //...
  toolbar.add(new ControlContribution("searchText") {
  //...

This works and I have the search field in the toolbar. But how can I align the search text (or the toolbar with the search text) on the right side?
Thanks,
Michael

A: If you mean positioning search toolbar on the right hand site of the main toolbar, then consider using these areas instead (when using org.eclipse.ui.menus extension point):
toolbar:org.eclipse.ui.main.toolbar - the top-level tool bar
toolbar:org.eclipse.ui.trim.command1 - the top left trim
toolbar:org.eclipse.ui.trim.command2 - the top right trim
toolbar:org.eclipse.ui.trim.vertical1 - the left vertical trim
toolbar:org.eclipse.ui.trim.vertical2 - the right vertical trim
toolbar:org.eclipse.ui.trim.status - the status line trim


text:
Q: What is the meaning of "&" when dealing with condition formula with cell reference rather than fixed numbers I want to count the number that the value in a specified group is bigger than some value (which is in another cell).
For example:
     A     B     C
  -------------------
1 |  5  |  4  |  3  |
2 |  5  |  2  |  1  |
3 |  6  |  4  |  3  |
4 |  7  |  5  |  5  |
5 |  3  |  6  |  6  |
6 |  1  |  9  |  8  |
  -------------------

I want to count:

*

*in the range of A2:A6, how many is greater than A1;

*in the range of B2:B6, how many is greater than B1;

*in the range of C2:C6, how many is greater than C1;

I input the following formula (found it via Google):
COUNTIF(A2:A6, ">"&A1)
Actually I do not understand what is this & symbol for in EXCEL. Can anyone explain this?
Thanks,

A: "&" is the concatenation operator. It joins two strings together and returns a string.
Edit
I recommend searching help for the CONCATENATE and COUNTIF functions. The latter doesn't explicitly specify that argument 2 must evaluate to a String but it is implied in COUNTIF function help under Common Problems.
The operators >; <; <>; must be embedded within double quotes "" or the string evaluation will fail.  You can CONCATENATE strings using the shorthand & character.
If you want to count the number of 5s in a range, 5 doesn't have to be in double quotes -  =COUNTIF(C1:C7,5) but if you put an equal sign before 5, they must be in quotes =COUNTIF(C1:C7,"=5")
COUNTIF(A2:A6, ">"&A1) evaluates to COUNTIF(A2:A6, ">5") whereas COUNTIF(A2:A6, >&A1) and COUNTIF(A2:A6, >5) will both throw errors.

A: You can't use the "&" symbol as and AND operator because it is the concatenation operator.
For your purpose you can just use the function COUNTIFS which is the same as COUNTIF but has many conditions to set.
Have a look at this examples to understand how easily it works.


text:
Q: Create IplImage with stride in Python I'm using the OpenCV bindings for Python. I would like to create an IplImage object from a buffer with a certain stride, which I cannot change without impacting on other components of my program. With the underlying C structure supports striding (which is called widthStep), the only Python constructor I could find (cv.CreateImage) doesn't support setting it.
Is there any way to set widthStep?
Thanks.


text:
Q: Find the frequency of a solution for the differential equation Suppose I have the following differential equation:
$$
\ddot{x} + x = \frac{k}{1-x}, \quad k>0, x(0) = 0, \dot{x}(0) = 0
$$
It is known that its solution is some periodic function. Is there a way to find the frequency of $x$ without solving the equation itself?


text:
Q: How (& where) to write out to files in springboot microservices on EKS? I have a Java Springboot microservice running on EKS.
I would like to generate a .tfvars file (Terraform runtime params file) inside my microservice and check in the same on Bitbucket.
I'm not sure where the file write out would create a file? Will it be inside the container OS file system? Or is having an EFS mandatory to be able to write out files?


text:
Q: Время конкретного пользователя в Java В коде имеется сервис, который разрешает/отклоняет HTTP запрос в зависимости от времени (до 11:00 разрешено, после - запрещено).
На текущий момент реализовано крайне просто:
public Vote vote(Restaurant restaurant, User user) {
    Vote voteFromRepo = voteRepository.findByUserIdAndDate(user.getId(), LocalDate.now());
    if (voteFromRepo != null && LocalTime.now().isAfter(LocalTime.of(11, 0))) {
        throw new VoteDenyException();
    }
    return voteRepository.save(new Vote(restaurant, user));
}

Как привязать проверку времени к часовому поясу пользователя, а не к системному времени?

A: Используйте LocalDateTime, там есть возможность задать TimeZone. В базе храните все даты в формате UTC, когда даты показываются пользователям отображаете им даты, приводя к их часовому поясу. В вашем случае в запросе отправляйте текущие дату,время и часовой пояс клиента.
Посмотреть как на клиенте получить дату и зону можно здесь https://stackoverflow.com/questions/1091372/getting-the-clients-timezone-offset-in-javascript


text:
Q: Ruby on Rails - concatenate strings on save to database upon user clicking create action Its late and I probably should sleep on this. Easy one
I have 3 fields in a form which a user fills in. Once they click the create button these records are saved to the database. Simple.
However I want the data from these three fields at the same time to be concatenated together, nothing fancy..and inserted to the database at the same time as the other records. This should reflect back to the user on the show page after they create.
So I need an action to concatenate 3 db columns lets say column names are firstname, surname and DOB. table name PeopleDetails
I have tried building the model using after_create, before_save, built into the model, but nada. suggestions. I think I will come back and revisit this after some sleep

A: Assuming you have a column (model attribute) called full_name than you can combine all together on a model create/save via:
class User < ActiveRecord::Base
  before_save :concatenate_details

  def concatenate_details
     self.full_name = "#{firstname} #{surname} #{dob}"
  end

end


text:
Q: Selenium Server 2.17.0 SessionCleanup after few hours I am always getting SessionCleanup after few hours. Because of the SessionCleanup, the test fails and Selenium is closed.
How do I stop executing SessionCleanup?
I found this but it is not fixed as mentioned:
http://code.google.com/p/selenium/issues/detail?id=3161
This error is in version 2.16.0 and 2.17.0
23.1.2012 9:48:52 org.openqa.grid.selenium.GridLauncher main
INFO: Launching a selenium grid server
23.1.2012 9:48:55 org.openqa.jetty.http.HttpServer doStart
INFO: Version Jetty/5.1.x
23.1.2012 9:48:55 org.openqa.jetty.util.FileResource <clinit>
INFO: Checking Resource aliases
23.1.2012 9:48:57 org.openqa.jetty.util.Container start
INFO: Started org.openqa.jetty.jetty.servlet.WebApplicationHandler@5e176f
23.1.2012 9:48:57 org.openqa.jetty.util.Container start
INFO: Started WebApplicationContext[/,/]
21.1.2012 9:48:57 org.openqa.jetty.http.SocketListener start
INFO: Started SocketListener on 0.0.0.0:4455
23.1.2012 9:48:57 org.openqa.jetty.util.Container start
INFO: Started org.openqa.jetty.jetty.Server@1971afc
23.1.2012 12:59:22 SessionCleanup
WARNING: session ext. key 1327135735339 has TIMED OUT and will be released

A: You can control and maximize the cleanupCycle at the client level when launching the node with the option -cleanupCycle 2147483647 (Java MAX_INT). According to the documentation, it doesn't look like you can prevent it entirely, but this will at least reduce the frequency to once every ~25 days if you have no other option.
Execute your jar with this command to see more options:
java -jar selenium-server-standalone-2.16.0.jar -help


text:
Q: Bot in Teams freeze I often experience that bots in Microsoft Teams freeze - they simply stop reponding. They still responds in other channels like Skype and Web. After a few hours they start responding again. Any help or input is appreciated.
SDK 4.0


text:
Q: I want to open an activity after my main activity has loaded I have a project where my manifest is opening .MainActivity by default
 <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

I want to be able to open an info screen on top of that app where it tells about my app. from there the user can press back to get back to the Main Activity.

A: You can start your info screen Activity in your MainActivity's onCreate() method with startActivity() method

A: Use an Intent in your MainActivity with a Button click or however you want the input to work
Intent intent = new Intent(MainActivity.this, NextActivityName.class);
 intent.putExtras("key", value);    // if you want to send data
 // other intent attributes such as flags
 startActivity(intent);
Intents
If you are stuck on how to change Activities then you really should Start Here and go through the docs carefully so you understand the basics of the Android framework


text:
Q: Ошибка обработки нажатия на кнопку Разрабатывают простенький сайт для занесения записей. При нажатии на кнопку и заполнении данных пишет что ошибка в index.php 25 строке, когда в документе их всего лишь 22.
Ошибка Parse error: syntax error, unexpected '1' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' in G:\Progi\serv xampp\htdocs\TrashMetall\2\index.php on line 25
Соединение.
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','rotokan123rot');
define('DB','auto_to_db');

//ALTER USER 'root'@'localhost' indentified with mysql_native_password BY 'rotokan123rot':

$con = mysqli_connect(HOST,USER,PASS,DB) or die ('Unable to Connect');

if(!$con)
{
echo 'Connection error == '.mysqli_connect_error();
}
else
{
echo "OK";
}

//?>

Добавление.
<?php
require_once('c.php');
$data_of_entry=$_POST['data_of_entry'];
$value=$_POST['value'];
$iduser1=$_POST['iduser1'];
$idcar=$_POST['idcar'];
$desCC=$_POST['desCC'];
$enable='1';
$sql="insert into mileages (data_of_entry,value,iduser1,idcar,desCC,enable) values ($data_of_entry,$value,$iduser1,$idcar,$desCC,$enable)";
//$sql="insert into mileages (data_of_entry,value,iduser1,idcar,desCC,enable) values ('1999-12-12','0','1','1','---','1')";
if(mysqli_query($con,$sql))
{
echo "Access";
}
else
{
echo "Fail";
}
mysqli_close($con);
header("Location: ../index.php?signup=success");
//?>

Сама страничка.
<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="widht=device-widht, initial-scale=1.0">
<meat http-equiv="X-UA-Compatible" content="ie-edge">
<title>WEB-интерфейс</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">

<form action="i.php" method="POST">

Форма аутентификации

<input type="text" name="data_of_entry" placeholder="Введите дату(гггг-мм-дд)">

<input type="text" name="value" placeholder="Введите значение">

<input type="text" name="iduser1" placeholder="Введите ид пользователя">

<input type="text" name="idcar" placeholder="Введите ид автомобиля">

<input type="text" name="desCC" placeholder="Введите замечание(необязательное поле)">

<button type="submit" name="submit">Войти</button>
</form>

A: Замените ваш <button type="submit" name="submit">Войти</button> на <input type="submit" name="submit" value="Войти"> и php коде добавление
if(mysqli_query($con,$sql)) { echo "Access"; }

на
if(isset($_POST['submit'])) { mysqli_query($con,$sql); echo "Access"; }


text:
Q: Adding Expires headers to favicon.ico using Nginx as proxy of node.js My site is running on node.js and I'm using Nginx to server my static files from a cookieless domain. For these files I have setup Nginx to set the expires headers. However it does not seem to be working for my favicon.
My Nginx default config file:
# static content
server {
        server_name static.domain.com;
        root /my/website/lives/here/public;

        location ~*  \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 365d;
        }
}

Ico has a minetype in mime.types:
image/x-icon    ico;

Service response headers showing no Cache-control or Expires:
Accept-Ranges:bytes
Connection:keep-alive
Content-Length:32988
Content-Type:image/x-icon
Date:Tue, 11 Dec 2012 23:20:19 GMT
Last-Modified:Sat, 08 Dec 2012 11:51:28 GMT
Server:nginx/1.1.19

And these are the response of a random image that has Cache-control and as Expires as you would expect:
Cache-Control:max-age=31536000
Connection:keep-alive
Date:Tue, 11 Dec 2012 23:24:00 GMT
Expires:Wed, 11 Dec 2013 23:24:00 GMT
Last-Modified:Tue, 11 Dec 2012 23:04:24 GMT
Server:nginx/1.1.19

I checked if the favicon was being served from the static domain (static.domain.com/favicon.ico) and not the websites document root (domain.com/favicon.ico). Does anyone have any idea what is wrong or how I could debug this?

A: Apparently there was another line matching the favicon, hidden in an include file, which I ommitted in the question for the sake of simplicity.
location = /favicon.ico {
    log_not_found   off;
    access_log  off;
}

Removing this (because there is favicon present on this site) solved my issue :-)


text:
Q: rails 5.2 Webpacker asset pipeline Hi I have been having trouble with an application i started using the jumpstart template from gorails.
I am finding that my I am struggling to get my js to work. For this example( there are many) I will use trix editor.
I follow the instructions
Add trix-rails to your Gemfile:
gem 'trix-rails', require: 'trix'

Run bundle install and restart your server to make the files available through the pipeline.
Import Trix styles in app/assets/stylesheets/application.css:
*= require trix

Require Trix Javascript magic in app/assets/javascripts/application.js:
//= require trix

but i get a blank box like so

Its starting to kill my vibe. and I am sure its because i dont fully understand how the pipeline works now with webpacker.
<%= simple_form_for(@article) do |f| %>
  <%= f.error_notification %>
  <%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>

    <%= f.input :title %>
    <%= f.input :content, as: :trix_editor %>

    <%= f.button :submit %>

<% end %>

any help would be appreciated. Because i am using webpacker should i be placing javascript and css somewhere else?

A: As far as I know, webpacker is not going through the asset pipeline.
If you have a Rails 5.x project, you can use the asset pipeline (check your Rails version in the gemfile) next to webpacker.
With the same boilerplate I made it work by following these steps:

*

*add to gemfile as you did and bundle install

*yarn add trix in the command line

*add @import "trix"; to app/assets/stylesheets/application.scss

*and then, because of the yarn install you can import it into the 'new' javascript folder app/javascript/packs/application.js like so: import 'trix'
With the same html code, the editor now shoes perfectly fine for me :)


text:
Q: Change color based on value from another table I have an answer sheet (in sheet tab "Answer Sheet") in Excel like this:

And I have this table for correct answers (in sheet tab "Correct Answer") like this:

I want to change the color for incorrect answers with red background.
And I want to create a "toggle" to show the incorrect answers (if I change the value to "TRUE"), maybe like this:

How do to it?

A: This can be done with the conditional formatting manager:
Start => Conditional Formatting => New Rule => Based on Formula (last option)
In the Formula you will click on the answer sheet in B2 and remove the "$" type "<>" (which stands for not equal) and then select B2 in the correct answer sheet:
= B2<>CorrectAnswer!B2
Then you will then change the format to the style you like and click ok.
Edit: to extend the area the formatting applies to, you can copy the formatting by using the formatting paster:
https://www.solveyourtech.com/copy-cell-formatting-from-one-cell-to-another-in-excel-2010/
or by extending the area it applies to after you defined the rule:
https://www.excel-easy.com/examples/images/manage-rules/conditional-formatting-rules-manager.png
Toggling:
This can be done in the manager by setting it to active or inactive. https://excelunplugged.files.wordpress.com/2014/06/060314_0545_turnconditi6.png
Alternatively: you could write the formula like this:
= and(B2<>CorrectAnswer!B2;$G$9=TRUE)


text:
Q: Can I change the tooltip's default action of Kendo UI grid in MVC? In the default action,When I put my mouse  on the  in the Tool tip column, the tooltip will show the content.But Now what I want  is only when I click the  ,it will show the content.And when I click the mouse outside the ,the content will disapper.The demo is here:demo

A: You just need to add showOn: "Click" and autoHide: false to the setup of the tooltip:
var toolTip = $('#grid').kendoTooltip({
     showOn: "click",
     autoHide: false,
    filter: ".tooltip",
    beforeShow: function (e) {
        if ($(e.target).data("name") === null) {
            // don't show the tooltip if the name attribute contains null
            e.preventDefault();
        }
    },
    content: function (e) {
        // may be get the content from server using ajax event
        var row = $(e.target).closest("tr");
        var dataItem = grid.dataItem(row);

        return "

dd

dd

Hi, this is a tool tip for id " + dataItem.Id + "!
";
    }
}).data("kendoTooltip");

Demo: http://jsfiddle.net/2dzUb/7/


text:
Q: Extends Interface NodeJS I have an Interface :
interface MyInterface {
  id: number;
  name: string;
  ...
}

I want to extends it in a forEach :
AllData.forEach((extendsInterface: MyInterface extends { newVar: string }) => {
   extendsInterface.newVar = "Hello World";
}

I have this error :  '?' Expected on the ) after { newVar: string }
Don't know what i'm doing wrong
Thanks !
EDIT :
If i create MyInterfaceExt outside the line, or use& instead of extends i have this error :
Argument of type '(extendsInterface: MyInterfaceExt) => void' is not assignable to parameter of type '(value: MyInterface, index: number, array: MyInterface[]) => void'.
Types of parameters 'extendsInterface' and 'value' are incompatible.
Property 'newVar' is missing in type 'MyInterface' but required in type 'MyInterfaceExt'

A: As stated in comments you can choose between:
interface MyInterfaceExt extends MyInterface {
  newVar?: string;
}

or if you wish to add inline, called intersection-type
MyInterface & { newVar?: string }


text:
Q: How do you iterate over children of a class in .Net? I have a C# .Net class RootObject which contains a number of lists of various object types. I get a json object from an ajax call and deserialize it into a RootObject instance. I would like to iterate over all the lists in my root object and create data tables for them to pass to a stored procedure, but I can't figure out how to do that. Can anyone help?
public class RootObject
{
    public List<Car> Car { get; set;}
    public List<Plane> Plane { get; set;}
    public List<Train> Train { get; set;}
}

    /// <summary>
    /// Returns a data table filled with the values from the input list
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <returns></returns>
    public DataTable CreateDataTable<T>(IEnumerable<T> list)
    {
        Type type = typeof(T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

    /// <summary>
    /// This function saves the layout specified by the the user with the ID specified
    /// </summary>
    /// <param name="encryptedBEMSID"></param>
    /// <param name="Layout"></param>
    /// <returns></returns>
    public string Save(string encryptedBEMSID, string Layout)
    {
        // Make a list of table variable parameters to hold the results of the deserialization
        List<SqlParameter> parameters = new List<SqlParameter>();

        // Deserialize the json object
        RootObject obj = JsonConvert.DeserializeObject<RootObject>(Layout);
        PropertyInfo[] objLists = obj.GetType().GetProperties();

        foreach (PropertyInfo pi in objLists)
        {
            string ObjectType = pi.Name; // This would be "Car", "Plane", or "Train"
            string UpperObjectType = ObjectType.ToUpper();

// HERE'S WHERE I NEED HELP! I'd Like to replace Car with the class specified by ObjectType
            List<Car> List = obj.Car;
            DataTable dt = CreateDataTable<Car>(List);

            // do stuff with the resulting data table

        }
    }

EDIT TO ADD JSON
{
    "Car": [
        {"name": "The General", "color": "red"},
        {"name": "Batmobile", "color": "blue"}
    ],
    "Plane": [
        {"name": "Air Force One", "color": "white"},
        {"name": "Spirit of St. Louis", "color": "gray"},
        {"name": "Wright Flyer", "color": "brown"}
    ],
    "Train": [
        {"name": "Orient Express", "color": "black"},
        {"name": "Ye Olde Bullet Train", "color": "orange"}
    ]
}

A: foreach(var vehicle in vehicles) { //iterate car, plane, train
    foreach(var instance in vehicle) { //iterate the general, batmobile, etc.
        /* do stuff */
    }
}

A: Assuming your objects are just {name, color} you could create a class for that, say, Vehicle and then deserialize into a Dictionary<string,List<Vehicle>>.
Now you can enumerate the dictionary easily and enumerate lists of Vehicles off each key.
If it's more complicated than the JSON you showed then you might be better off reading the JSON directly (using Json.NET) and handling it that way.
You could also add a type discriminator to your JSON (see https://www.mallibone.com/post/serialize-object-inheritance-with-json.net) and then Json.NET will know that the Car field contains Car objects (a fact implied but not stated in your current JSON schema). You may also be able to provide a custom serialization binder that handles your special situation with types defined by field names. You'd still need a base class Vehicle but the actual deserialized value would be of the type expected.
And, yet another option might be to use a Dictionary<string, Dictionary<string, object>> to hold the deserialized JSON since all you are doing is copying the values to a table anyway - you don't care that it's a Car, it's just a collection of names and values.

A: If you move your datatable creation into a generic class VehicleHandler<T> you can create an instance of it with a matching type T to the type of the property you are currently examining like so:-
Type vehicleListType = pi.PropertyType;
Type vehicleType = vehicleListType.GetGenericArguments()[0];
var vehicleHandlerType = typeof (VehicleHandler<>).MakeGenericType(vehicleType);
var vehicleHandler = (VehicleHandler)Activator.CreateInstance(vehicleHandlerType);

And now, you can set the vehicles for this field and generate the data table:
vehicleHandler.SetVehicles(pi.GetValue(obj));
var dataTable = vehicleHandler.DataTable;

And the code for VehicleHandler is:
public abstract class VehicleHandler
{
    public abstract void SetVehicles(object listOfVehicles);
    public abstract DataTable DataTable { get; }
}

public class VehicleHandler<T> : VehicleHandler
{
    List<T> vehicles;

    public override void SetVehicles (object listOfVehicles)
    {
        this.vehicles = (List<T>) listOfVehicles;
    }

    public override DataTable DataTable => CreateDataTable(vehicles);

    public DataTable CreateDataTable(IEnumerable<T> list)
    {
        Type type = typeof (T);
        var properties = type.GetProperties();

        DataTable dataTable = new DataTable();
        foreach (PropertyInfo info in properties)
        {
            dataTable.Columns.Add(new DataColumn(info.Name,
                Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
        }

        foreach (T entity in list)
        {
            object[] values = new object[properties.Length];
            for (int i = 0; i < properties.Length; i++)
            {
                values[i] = properties[i].GetValue(entity);
            }

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

}


text:
Q: How do i validate XML against a schema (php or perl or possible C++) I need to take in XML and validate it against a schema file. Afterward i must call a function based on the command (example updateContactList). What is the best way to do this? I am worried about validating the XML (and report errors) and i have no idea what is the best way to put the data into a function to run
-edit- NOTE: By validating the schema i need to validate the (regex) pattern. It would be great if i can call a function with the XML and schema and have it return false + error msg or true

A: I'm not sure what you mean by regex pattern? The most common way to validate an XML document is trough an XSD. You can use DomDocument->schemaValidate for this:
$doc = new DOMDocument();
$doc->load($tempFile);
$doc->schemaValidate('schema.xsd');

There is also the corresponding DomDocument->relaxNGValidate for validating against the lesser used RelaxNG schema.
You may also want to use the error-handler functions for libxml, if you plan on capturing the errors and doing something about them, rather than just validate true or false. In essence, call libxml_use_internal_errors(true); before loading and validating the document, and use libxml_get_errors and display_xml_error to fetch the errors.


text:
Q: Image Position/Orientation not written when saving itkImage as DICOM I have a 3D volume as itkImage<unsigned char, 3> and want to save it as DICOM series. Saving the series works so far, but the metadata tags "Image Position Patient" and "Image Orientation Patient" are not saved in the dicom file. All other tags are saved correctly.
If I print the metadata dictionary to the console these tags are printed correctly. When I open the files in ITK-SNAP these two tags are missin.

0010|0010 Patient
0010|0020 12345
0020|0032 0\0\0
0020|0037 1\0\0\0\1\0

This is the part of the code where these tags are stored in the metadata. I created a gist with a working example.
UC3ImageType::PointType position;
UC3ImageType::IndexType index;
index[0] = 0;
index[1] = 0;
index[2] = f;
image->TransformIndexToPhysicalPoint(index, position);
value.str("");
value << position[0] << "\\" << position[1] << "\\" << position[2];
itk::EncapsulateMetaData<std::string>(*dictionary, "0020|0032", value.str());
value.str("");
value << position[2];
itk::EncapsulateMetaData<std::string>(*dictionary, "0020|1041", value.str());

itk::EncapsulateMetaData<std::string>(*dictionary, "0020|0037", "1\\0\\0\\0\\1\\0");

What's wrong with this code? Are there other tags that are required, such that these tags are saved as well?

A: I could solve the problem by specifying a different SOP Class UID. By default it's using Secondary Capture IOD and I changed it to Ultrasound Multi Frame, which is also more apropriate for my image. Now the Image Orientation/Position are stored correctly.
const std::string SOP_CLASS_UID = "0008|0016";
const std::string US_MULTIFRAME_UID = "1.2.840.10008.5.1.4.1.1.3.1";
itk::EncapsulateMetaData<std::string>(*dictionary, SOP_CLASS_UID, US_MULTIFRAME_UID);

However, to me it's still strange, that there is no warning or exception when a metadata tag is not saved due to whatever reason.


text:
Q: Call sql query synchrously Currently working on node rest api project where I want to fetch data for a list of data. for example : I have a list of post_id([1,2,3....]) for a particular tag(mobile) and for each post_id I want to retrieve post title and description from mysql database. But calling sql query is synchrounous.
How to control flow for each post id result to combine in one.
my db calling code is here :
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');    // call body-parser
var addData = require('./dbhandler/addData'); // call database handler to insertdata
var getData = require('./dbhandler/getData');

//route function to get feeds by tags
router.route('/postfeedsbytags/:tag')
// get all new article feeds filtered by tag
.get(function(req,res){
    var success;
    console.log(req.params.tag)
    var json_results = [];
    getData.getPostFeedsByTag(req.params.tag,function(error, results, fields){
        if (!error){
            for (var i = 0; i < results.length; i++) {
                getData.getPostFeedsByPostId(results[0]['post_id'],function(error, results, fields){
                    if (!error){
                        success = 1;
                        json_results.push(results[0]);
                        res.json({"success" : success, "datasets" : json_results});
                    } else{
                        success = 0;
                        console.log('Error while performing Query.'+error);
                        res.json({"success" : success});
                    }
                });
            }
            // res.json({"success" : success, "datasets" : results});
        } else{
            success = 0;
            console.log('Error while performing Query.'+error);
            res.json({"success" : success});
        }
    });
});

A: I think you can use the IN operator in the query to get all the posts in a single query and then iterate over it.
If you don't want to use IN operator then use async library for flow control. You can use the async.map function from it.


text:
Q: How can I parse a string from an object inside square brackets I'm doing an api call that is resulting in an object inside square brackets.
Code:
        request.get(options, function(error, response, body) {

            var JSONdata = (JSON.stringify(body));
            var trip = JSON.parse(JSONdata).results;
            console.log(trip);

    });

Log:
[ { id: 'T_ec926d18c46e39d9',
url: 'https://api.automatic.com/trip/T_ec926d18c46e39d9/',
driver: 'https://api.automatic.com/user/U_0c1ee2ddcfea14be/',
vehicle: 'https://api.automatic.com/vehicle/C_7e050c914a0d2b97/',
duration_s: 447.3,
distance_m: 3375.3,
started_at: '2017-10-31T02:11:58.607000Z',
ended_at: '2017-10-31T02:19:25.918000Z',
start_timezone: 'America/Toronto',
end_timezone: 'America/Toronto',
tags: [],
idling_time_s: 0,
user: 'https://api.automatic.com/user/U_0c1ee2ddcfea14be/' } ]

I'm trying to parse the "distance_m" out of this object but converting it to a string results in:
    [{"id":"T_ec926d18c46e39d9","url":"https://api.automatic.com        /trip/T_ec926d18c46e39d9/","driver":"https://api.automatic.com/user/U_0c1ee2ddcfea14be/","vehicle":"https://api.automatic.com/vehicle/C_7e050c914a0d2b97/","duration_s":447.3,"distance_m":3375.3,"started_at":"2017-10-31T02:11:58.607000Z","ended_at":"2017-10-31T02:19:25.918000Z","start_timezone":"America/Toronto","end_timezone":"America/Toronto","tags":[],"idling_time_s":0,"user":"https://api.automatic.com/user/U_0c1ee2ddcfea14be/"}]

which I cannot parse anything out of (I'm assuming because of the square brackets)
I've tried replacing the square brackets with regex but that does not work either (as showed here: How to remove square brackets in string using regex?)
How can I extract the "distance_m" value to a variable?

A: The square brackets represent an array - if you only need the first item you can access this very simply:
trip[0].distance_m


text:
Q: Removing all traces of a UIView I've got another question.
I've got this NavigationController, which has a delegate: MainViewController.
In this navigation controller, there's a table view, which has the same delegate: MainViewController.
Whenever I press a row in the table, a view pops up called: itemViewController.
Now, this all works really great. But when I press back, I want the itemViewController + it's view to be completely forgotten, it has to be destroyed 100%. Like it has never even existed.
which has a logical background: Whenever im done with the view, i press back. And when i want to see it again, i want it to be reloaded, i do not want an old reference to the view to be used, because the data it shows is changing all the time. So, in my situation right now, i have to relaunch the app to see the new data in the view.
Which, i find, really frustrating.  So help me out, how can I make sure that view is deleted, and reloaded completely when i click on it again from the table view?

A: Depends on how you have the reference to the itemViewController coded.
In general, [itemViewController release]; will remove the reference to the view controller.
The will mean that the next time you need the itemViewController, you will have to re-create it from scratch (e.g. [[itemViewController alloc] initWithNib: . . . . ] )
Another option you might consider would be setting up properties for the itemViewController and simply keeping the reference around and updating the properties before you push it into view.
Hard to give a definitive answer without seeing your code.


text:
Q: ruby on rails rspec command So as a beginner I am following Michael Hart's ruby on rails 2nd edition tutorial !
when I run command line with the integration test module
rspec test/integration/static_pages_test.rb

it's not showing what Hartl's getting. Instead it's showing this :
/Users/Name/rails_testprojects/protego/test/integration/static_pages_test.rb:1:in `require': no such file to load -- test_helper (LoadError)
    from /Users/Name/rails_testprojects/protego/test/integration/static_pages_test.rb:1:in `<top (required)>'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `block in load_spec_files'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `map'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load_spec_files'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/command_line.rb:22:in `run'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:69:in `run'
    from /Users/Name/.rvm/gems/ruby-1.9.2-p320@twitclone/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:8:in `block in autorun'

Note : In Hartl's tutorial , the integration test is in a different folder called !
bundle exec rspec spec/requests/static_pages_spec.rb

can someone please explain what's going on ? I am a total beginner and have just started following his tutorials !

A: You say you're following Michael Hartl's Rails Tutorial book, but you really aren't following it; at least not as rigorously as required ;-)
Rails Tutorial book uses RSpec as the testing framework of choice. In rspec, all the test files are under spec folder, and are called specs.
Rails by default comes with Test::Unit testing framework, and it places the files under test folder.
You are mixing both of them and are getting confused.
I suggest you to stick with what's there in Rails Tutorial book, and rigorously follow the instructions there to get the most out of your time spent in learning rails.


text:
Q: Proof that $f(x)=x|x|$ is differentiable on $\mathbb{R}$ I want to show that
$$f(x) = x|x|$$
is differentiable for all reals.
My approach would be:
Since $ \forall x \in \mathbb{R}$ such that $x < 0$ we have $f(x) = -x^2$ which is differentiable.
also $\forall x \in \mathbb{R}$ such that $x > 0$ we have $f(x) = x^2$ which is also differentiable.
Last but not least I would have to show that $f$ is differentiable at $x=0$ and from this it would follow that $f$ is differentiable $\forall x \in \mathbb{R}$ and of course also continuous.
Is this correct?

A: Yes. If you prove the differentiability at $x<0, x>0$ and $x=0$ then $f$ is differentiable.

A: $f(x)=x|x|= x^2, x>0; -x^2, x<0.$  It being a two piece function only $x=0$ is suspected for a non differentiability. So the right derivative at $x=0$ is $Rf'(0)=0$ and the left derivative at $x=0$ is $Lf'(0)=0$. Since both of them are equal and finite $f(x)$ is differentiable at $x=0$ and everywhere.


text:
Q: How to inline radio buttons in a django form? Here's the radio buttons:
account_type = forms.ChoiceField(
    choices=enumerate(('Choice 1', 'Choice 2')),
    widget=forms.RadioSelect(
        {'class': 'form-check form-check-inline', 'style': 'margin-left: 20px'}
    ),
    label='',
)

I'm using bootstrap-nightshade for styling which possibly contains something that prevents inlining the buttons. So far I tried:
display: inline

and
display: inline-block;

and
class="radio-inline"

Nothing works. Here's the template of the form
{% extends 'index.html' %}
{% load bootstrap5 %}

{% block content %}

{{ form_title }}

                            <form method="post">
                                {% csrf_token %}
                                {% bootstrap_form form %}
                                <button class="btn btn-success">{{ form_title }}</button>
                                {% if form_title == 'Sign in' %}
                                    Forgot password?
                                {% endif %}
                            </form>

{% endblock %}

and here's how they are rendered:

            <input class="form-check form-check-inline" id="id_choices_0"
                                                  name="choices" required="" style="margin-left: 20px" title=""
                                                  type="radio" value="0">
                Choice 1

            <input class="form-check form-check-inline" id="id_choices_1"
                                                  name="choices" required="" style="margin-left: 20px" title=""
                                                  type="radio" value="1">
                Choice 2


text:
Q: How can you require an undetermined character to be repeated consecutively a certain number of times in Ruby Treetop? I want to create a rule that requires a non-number, non-letter character to be consecutively repeated three times. The rule would look something like this:
# Note, this code does not do what I want!

grammar ThreeCharacters

  rule threeConsecutiveCharacters
    (![a-zA-Z0-9] .) 3..3
  end

end

Is there any way to require the first character that it detects to be repeated three times?
There was previously a similar question about detecting the number of indentations: PEG for Python style indentation
The solution there was to first initialize the indentation stack:
&{|s| @indents = [-1] }

Then save the indentation for the current line:
&{|s|
  level = s[0].indentation.text_value.length
  @indents << level
  true
}

Whenever a new line begins it peeks at the indentation like this:
!{|s|
  # Peek at the following indentation:
  save = index; i = _nt_indentation; index = save
  # We're closing if the indentation is less or the same as our enclosing block's:
  closing = i.text_value.length <= @indents.last
}

If the indentation is larger it adds the new indentation level to the stack.
I could create something similar for my problem, but this seems like a very tedious way to solve it.
Are there any other ways to create my rule?

A: Yes, you can do it this way in Treetop. This kind of thing not generally possible with a PEG because of the way packrat parsing works; it's greedy but you need to limit its greed using semantic information from earlier in the parse. It's only the addition in Treetop of semantic predicates (&{...}} that make it possible. So yes, it's tedious. You might consider using Rattler instead, as it has a significant number of features in addition to those available in Treetop. I can't advise (as maintainer of Treetop, but not being a user of Rattler) but I am very impressed by its feature set and I think it will handle this case better.
If you proceed with Treetop, bear in mind that every semantic predicate should return a boolean value indicating success or failure. This is not explicit in the initialisation of @indents above.


text:
Q: running pyinstaller after Anaconda install results in ImportError: no Module named 'pefile' I did conda install -c acellera pyinstaller=3.2.3 as per Anaconda's website and it looks like it installed correctly but I get the following if I try to run it via cmd:
C:\Users\Cornelis Dirk Haupt\PycharmProjects\Mesoscale-Brain-Explorer\src>pyinstaller
Traceback (most recent call last):
  File "C:\Anaconda3\Scripts\pyinstaller-script.py", line 9, in <module>
    load_entry_point('PyInstaller==3.3.dev0+g8756735', 'console_scripts', 'pyinstaller')()
  File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 542, in load_entry_point
  File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2569, in load_entry_point
  File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2229, in load
  File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2235, in resolve
  File "C:\Anaconda3\lib\site-packages\PyInstaller\__main__.py", line 21, in <module>
    import PyInstaller.building.build_main
  File "C:\Anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 34, in <module>
    from .api import PYZ, EXE, COLLECT, MERGE
  File "C:\Anaconda3\lib\site-packages\PyInstaller\building\api.py", line 38, in <module>
    from PyInstaller.utils.win32 import winmanifest, icon, versioninfo, winresource
  File "C:\Anaconda3\lib\site-packages\PyInstaller\utils\win32\versioninfo.py", line 17, in <module>
    import pefile
ImportError: No module named 'pefile'

What's going on? Pyinstaller works fine with python 2.7 without Anaconda. But I've recently decided to make the jump to Anaconda + 3.5. I cant find any module named pefile or how to install it with Anaconda. I can install pefile easily using pip3 though.

A: You can use Anaconda's pip to install it, just go to the Script folder in Anaconda and execute:
pip.exe install pefile

A: install this instead:
conda install -c conda-forge pyinstaller=3.2.1

working fine for me after a couple of tries!


text:
Q: How solve django-admin is not recognized...? I'm trying:
Django-admin startproject myweb
This is what i see:
'django-admin' is not recognized as the name of a cmdlet,
function, script file, or operable

Even i added python27/Scripts to my pc environment variables but didn't work

A: First, you need to run pip install django first without activating virtual env, if you want to install django only in virtual env then you have to activate it first and then get django installed into that only after trigger the command django-admin startproject myweb

A: Here is the solution to your problem: You can do this using virtualenv. step by step

*

*py -m pip install --user virtualenv

*py -m venv env

*.\env\Scripts\activate

*python -m pip install Django
check version:

*

*python -m django --version
start project Command:

*

*django-admin startproject mysite
start app Command:

*

*python manage.py startapp myapp
now you can run project:

*

*python manage.py runserver
http://127.0.0.1:8000/


text:
Q: Alignment of two equations on LaTeX I'm trying to get two equations aligned via the equals sign, this is my code so far:
\begin{align}
\int_0^1 xJ_v(\lambda x)J_v(\mu x) \mathrm{d}x &= \frac{\mu J_v(\lambda)J^{\prime}_v(\mu) - \lambda J_v (\mu)J^{\prime}_v(\lambda)}{\lambda^2 - \mu^2}
\\[5mm]
\int_0^1 x[J_v(\lambda x)]^2 \mathrm{d}x &= [J_{v+1}(\lambda)]^2 + \left( \frac{\lambda^2 - v^2}{2 \lambda^2} \right)[J_v(\lambda)]^2,
\end{align}

I've tried using & and also \begin{align} but it doesn't seem to work. Any help?

A: Right click on the displayed expression below, select Show Math As, and then select TeX Commands.
\begin{align*}
\int_0^1 xJ_v(\lambda x)J_v(\mu x) \mathrm{d}x &= \frac{\mu J_v(\lambda)J^{\prime}_v(\mu) - \lambda J_v (\mu)J^{\prime}_v(\lambda)}{\lambda^2 - \mu^2}\;,\\\\
\int_0^1 x[J_v(\lambda x)]^2 \mathrm{d}x &= [J_{v+1}(\lambda)]^2 + \left( \frac{\lambda^2 - v^2}{2 \lambda^2} \right)[J_v(\lambda)]^2\;,
\end{align*}

A: In general to align equations, it goes like:
Document text here.
\begin{align}
  \label{eq1} x^2 & = y^2 \\
  \label{eq2} x^2 & = y^2 \\
  \label{eq3} x^2 & = y^2
\end{align}

If you want the equations to not be numbered, take out the label commands and don't write the * at the end of align. Note that you don't need to use other commands to enter and exit the math environment, such as $$ or the commands
\begin{equation}
\end{equation}


text:
Q: Can anyone explain in simple and easy words that what is the difference between ../ and ./ when including files? As we know that ../ means one step back and / means the current place but i am confused about the ./ when working with my web site and found that. Can anyone explain ?

A: . means this directory
.. means the parent directory
/ is the directory separator (for Linux/Unix)
When using include "file.php"; php will look in the current directory and in his configured include path for a file named file.php
When using include "./file.php"; php will look in the current directory (and only there) for a file named file.php
if you use include "../file.php"; php will look in the parent directory for a file named file.php

A: ./ - current directory.

/ - it is root directory (it used often for concatenating paths as directory separator, because previous path doesn't contain leading slash, for example host + '/' + cssFile).

A: *

*/ represents the root of a folder structure. For a website, it's the
root folder, where you would usually put the index.html of the
landing page.

*./ represents the 'current' folder, relative with the
current file. If you open the 'index.html' file in the root folder,
then ./ will be the same as /. If you are in a subfolder of the
root, like /css/ for example, then ./ will be the same as
/css/.

*../ represents the parent folder. If you are in /css/,
then ../ will be the same as /, the root folder.

A: Lets say this is your working on a file called process.php in the following directory:
/app/form/process.php
The this is what those symbols mean:
/ = root directory, or in the example: /
./ = current directory, or in the example: /app/form/
../ = one directory back, in the example: app/


text:
Q: On automorphisms group of some finite 2-groups Let $G$ be a finite 2-group of nilpotency class 2 such that $\frac{G}{Z(G)}\simeq C_{2}\times C_{2}$.
I want information about its automorphisms group.
Please guide me.
Thank you


text:
Q: Brightness adjuster not found in control panel I cant seem to find the brightness adjuster in my laptop after I reformatted it with windows 7  ROG Rampage(64 bit). My laptop is HP Pavilion dm4-1209tx. I also checked with the HP website and my drivers are all up to date. I also tried installing HP Quick Launch but was unable to do so probably because it is not supported by my OS. I've run out of ideas anymore. Any advice? Thanks!

A: I've had the same problem once. For me, the trouble maker was TeamViewer's mirror driver. Uninstalling the mirror driver fixed the problem for me and the brightness adjust controls started working again.
I've contacted TeamViewer about this problem and it has been confirmed by TeamViewer support staff although they don't consider it a bug. Here's their response:

Thank you for your interest in TeamViewer.
This is a known issue, if the monitor driver is installed you lose
  your brightness settings. IF you want to recover them, you need to
  uninstall this driver and restart your computer.
If we may of further assistance, please don't hesitate to contact us
  again.

To uninstall the monitor driver, follow these steps:

*

*Start TeamViewer

*Under Extras → Options → Advanced → Show advanced options, look for Advanced network settings and click on the Uninstall button beside Install monitor driver
If you don't have TeamViewer on your computer, make sure you don't also have similar software (LogMeIn, RealVNC, etc.) that can install a monitor driver. To check if your computer's monitor is using one of these mirror drivers, do the following:

*

*Start Device Manager (Win+R → "devmgmt.msc" → OK)

*Find your computer monitor under "Monitors"

*Double click on the device and check if the properties windows says something like this:

If it does, you need to find and uninstall the respective monitor driver.

A: Quick analysis
When Windows can't find the correct driver for a graphic card it will use the Standard VGA Graphics Adapter driver, which is generic and provides basic video functionality only.
According to the official specifications, the laptop has switchable graphic cards.
This means the computer actually got two different graphics cards: Intel HD Graphics and AMD Radeon HD 6370M. The first one is integrated into the CPU and is energy efficient; the second one is discrete (or dedicated) and is more powerful.
The system can let you choose which graphic card to use, while defaulting to the integrated one to prolong battery life. Switchable solutions are based on custom hardware, and require specific drivers provided by manufacturers in order to work as intended.
Additionally, the the brightness adjustment was available before formatting. This suggests that the issue can be tracked down to a missing driver.
Further reading

*

*What is "switchable graphics cards" in laptops?

*Graphics processing unit - GPU forms

Resolution
Some manufacturers provide automated tools to check whether the drivers are up-to-date, but sometimes they might fail to properly detect the installed hardware, thus requiring  manual intervention.

*

*Download an install the latest graphics drivers available:

*

*Windows 7 x86 (32-bit)
http://h10025.www1.hp.com/ewfrf/wc/softwareCategory?os=4062&lc=en&cc=us&dlc=en&sw_lang=&product=5040973

*Windows 7 x64 (64-bit)
http://h10025.www1.hp.com/ewfrf/wc/softwareCategory?os=4063&lc=en&cc=us&dlc=en&sw_lang=&product=5040973

*Restart Windows.

A: There are two ways to in-/ decrease the backlight of the display. One is by installing the HP Hotkey drivers, so you can use fn +  whatever key it is on your laptop (sometimesF3 and F4, other times arrow up and arrow down.
The second way that does not require any installation, is by manually changing the setting. This article will go about doing that.

*

*Right click an empty spaece on the desktop and choose Personalize

*On the bottom right, click Screen Saver

*On the bottom, click Change power settings

*Click the Change plan settings on the right side of the powerplan you want to use. (I recommend using High performance if you use the laptop daily and mostly connected to a wall-outlet. (you can find it by clicking Show additional plans)

*Click Change advanced power settings

*Use the slider for Adjust plan brightness on both On Battery and Plugged in to change the brightness.

A: I can't stand Microsoft flaws. And or driver issues for not getting along with Microsoft. Who knows but I have the same problem the brightness controls completely disappear and the screen defaults to very bright.
In device manager the quickest way I found was to simply disable your display adapters and enable them instantly. This reboots the drivers and brightness control will be back to normal. But for how long that's the problem. Changing drivers and all the mentioning of power settings is absolutely useless and I wish people that haven't experienced a cure for this would stop leading everyone around in circles. That is why I am writing this.
I have not found the cure it's pissing me off.I only found this quick reboot fix because I am a technician but I am not God. Nobody technically will address this problem but I would love to hear from someone who will propose a genuine fix but truthfully I don't think there is one which means the fix I came up with is probably mine and yours best idea.


text:
Q: Date Range Report - Aggregation I have a few issues doing a typical report style SQL that I'm hoping someone with more experience might be able to help with.
I have the following tables
products

*

*product_id

*product_name

*product_category

product_defects

*

*product_id

*defect_date

*high_priority

*med_priority

*low_priority

calendar

*

*date

And what I want is to be able to generate a report that outlines the number of high / medium / low defects associated with each product category on each day e.g – even though data may not exist in product_defect for a particular day, in which case it should be returned as 0. Example:

product_category | date | high | medium | low
1 2012-10-01 1 5 6
2 2012-10-01 2 4 3
3 2012-10-01 1 5 6
1 2012-10-02 0 0 0
2 2012-10-02 2 4 3
3 2012-10-02 1 5 6
…

What I've done so far is:

*

*Create a lookup table called calendar which has a series of days in it going back/forward several years

*Right joined the lookup/product_defects table to get a series of dates so missing days can be marked as 0

*Used COALESCE and SUM to calculate totals and change any missing data to 0

*Used MIN / MAX on the defect_date to get the exact report range

I've banged my head on this for a few days now, hoping someone can help.
Thank you

A: You need to start with all combinations of products and dates, and then join in the defects:
select p.product_category, c.date,
       coalesce(SUM(high_priority), 0) as high_priority,
       coalesce(SUM(med_priority), 0) as med_priority,
       coalesce(SUM(low_priority), 0) as low_priority
from product p cross join
     calendar c left outer join
     product_defects pd
     on pd.product_id = p.product_id and
        pd.date = c.date
group by p.product_category, c.date
order by 2, 1

(Note:  this is untested, so may have syntax errors.)

A: something like this. I used dual instead of calendar which you can use or substitute calendar table.
eg with start date as 01-jan-2013 through to 15th jan 2013.
with dates as (select to_date('01/01/2013', 'dd/mm/yyyy') + rownum - 1 dte
                 from dual
               connect by level <= to_date('15/01/2013', 'dd/mm/yyyy')
                         - to_date('01/01/2013', 'dd/mm/yyyy') + 1)
select dt.dte, p.product_id, p.product_name,
       sum(d.high_priority), sum(d.med_priority), sum(d.low_priority)
  from products p
       inner join product_defects d
               on d.product_id = p.product_id
       right outer join dates dt
                     on dt.dte = d.defect_date -- trunc(d.defect_date) if you store with a time element.
 group by dt.dte, p.product_id, p.product_name
 order by dt.dte;

A: So this uses a sub-factory querying clause (cte) to aggregate all the defects for each category for each day.  I used this construct to make the logic clearer; there are other ways to do it.  The sub-query is then outer-joined to the calendar table.
with cte as
    ( select p.product_category
             , d.defect_date
             , sum(pd.high_priority) as high_priority
             , sum(pd.med_priority) as med_priority
             , sum(pd.low_priority) as low_priority
      from product p
           join product_defect pd
                on (pd.product_id = p.product_id )
     group by p.product_category
             , d.defect_date )
select cte.product_category
       , cal.date
       , nvl(cte.high_priority, 0) as high_priority
       , nvl(cte.med_priority, 0) as med_priority
       , nvl(cte.low_priority, 0) as low_priority
from calendar cal
     left outer join cte
        on cal.date = cte.defect_date
order by cte.product_category
       , cal.date

A: Calendar table example only. Increase the number of months back from -24 (2 years) to any number - copy/paste the code:
-- 2 years back by date  --
SELECT TRUNC(SYSDATE, 'YEAR') - LEVEL AS mydate
 FROM dual
CONNECT BY LEVEL <= TRUNC(SYSDATE, 'yy') - TRUNC(Add_Months(SYSDATE, -24), 'yy')
/

Add more dates:
-- 2 years back by date and week  --
SELECT mydate
 , TRUNC(mydate, 'iw') wk_starts
 , TRUNC(mydate, 'iw') + 7 - 1/86400 wk_ends
 , TO_NUMBER (TO_CHAR (mydate, 'IW')) ISO_wk#
FROM
(
SELECT TRUNC(SYSDATE, 'YEAR') - LEVEL AS mydate
  FROM dual
CONNECT BY LEVEL <= TRUNC(SYSDATE, 'yy') - TRUNC(Add_Months(SYSDATE, -24), 'yy')
)
/

Post create table and inserts scripts to answer the rest of your questions or use sqlfiddle...


text:
Q: JMS\Serializer\Exception\RuntimeException: Resources are not supported in serialized data. Path: Monolog\Handler\StreamHandler -> etc I'm working with Symfony 4 and i have installed JMS serializer with FOSRest bundle.
So every time i've got an error i've got this message :

JMS\Serializer\Exception\RuntimeException: Resources are not supported in serialized data. Path: Monolog\Handler\StreamHandler -> Symfony\Bridge\Monolog\Logger -> Symfony\Component\Cache\Adapter\PhpFilesAdapter -> Symfony\Component\Cache\Adapter\TraceableAdapter -> Symfony\Component\Cache\Adapter\PhpArrayAdapter -> Symfony\Component\Cache\DoctrineProvider -> Doctrine\Common\Annotations\CachedReader -> Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener -> Symfony\Component\EventDispatcher\EventDispatcher -> Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher -> ContainerYCXy4ht\srcTestDebugProjectContainer -> FOS\RestBundle\Request\ParamFetcher -> Symfony\Component\HttpFoundation\ParameterBag -> Symfony\Component\HttpFoundation\Request -> Symfony\Component\HttpKernel\Exception\HttpException

And after the real error and i dont understand why ? I use JMS contrib recipe :
/packages/dev/jms_serializer.yaml
jms_serializer:
visitors:
    json:
        options:
            - JSON_PRETTY_PRINT
            - JSON_UNESCAPED_SLASHES
            - JSON_PRESERVE_ZERO_FRACTION

/packages/prod/jms_serializer.yaml
jms_serializer:
visitors:
    json:
        options:
            - JSON_UNESCAPED_SLASHES
            - JSON_PRESERVE_ZERO_FRACTION

/packages/jms_serializer
jms_serializer:
visitors:
    xml:
        format_output: '%kernel.debug%'

So i don't understand why this behavior ?
If someone could help me ?
Thanks by advance

A: I found the solution it was an fos_rest configuration error
Before
fos_rest:
exception:
    enabled: true
    exception_controller: 'fos_rest.exception.controller:showAction'
param_fetcher_listener: force
body_listener: true
format_listener:
    enabled: true
    rules:
        - { path: '^/api', priorities: ['json'], prefer_extension: true}
        - { path: '^/', priorities: [ 'html', '*/*'], fallback_format: html, prefer_extension: true }
view:
    view_response_listener: 'force'

After
fos_rest:
param_fetcher_listener: force
format_listener:
    enabled: true
    rules:
        - { path: '^/api', priorities: ['json'], prefer_extension: true}
        - { path: '^/', priorities: [ 'html', '*/*'], fallback_format: html, prefer_extension: true }
view:
    view_response_listener: 'force'


text:
Q: how can i create excel file with only python standard library I want to create Excel file in python. But when search (openPyxl, xlsxwriter) only see and that's need to install. Have another ways to create excel file like a csv?
I know that's simple question I just want to know why cannot create or I want to try if another way having..
Thanks for help...

A: Writing csv-files would be a lot easier, as they are just comma-separated and line break is just a line break. So just looping through the data with for loop and writing into the file. Xlsx-files contain a lot of other information such as metadata etc., which would make it more difficult to write without any libraries (see e.g. the source of openpyxl).
with open('demo.csv', 'a') as file:
for i in range(0, 5):
    for j in range(0, 5):
        file.write(f'{i * j};')
    file.write('\n')

Semicolumn is due to excel csv having it as a delimiter.

A: If you want to use only the standard library to create a CSV-file you can take a look at CSV
Some example code from the site is:
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])


text:
Q: MYSQL /SQL multiple alias base on column values I have three tables: states (id, name); hospitals (id, name, level_id, state_id); level (id, name). The table (level) shows the quality of each hospital. A States can have several hospitals that have different quality of service (level). I want to achieve a MySQL query like below
Tables :
level
id| name    |
1 | level 1 |
2 | level 2 |
3 | level 3 |

hospitals
id| name | level_id | state_id
1 | Hos A| 1        | 22
2 | Hos B| 3        | 7
3 | Hos C| 2        | 13
...

result:
states | level 1 | level 2| level 3 | total
state 1| 0       | 1      | 1       | 2
state 2| 3       | 4      | 7       | 14
...

I have tried something along this line but just got stuck. Any help will be appreciated
SELECT state.name states, hos.level_id 'level 1', hos.level_id 'level 2', hos.level_id 'level 3'
FROM state

LEFT JOIN hospital hos ON hos.state_id = state.id

ORDER BY state.name

A: Is this what you want?
select state,
       sum(level_id = 1) as num_1,
       sum(level_id = 2) as num_2,
       sum(level_id = 3) as num_3,
       count(*) as total
from hospitals h
group by state;


text:
Q: SharePoint 2013 task url issue Possible Duplicate
I am working on SharePoint 2013 visual studio workflow, while creating the single task activity email body, I am using

'%TaskSpecial: TaskUrl%'

token
my Task

but the token is pointing to the internal URL, while the environment is mapped to a external URL.
Are there any other special token that I am missing or I have to generate the url?

A: You will need to change the AAM to have the external url as the DEFAULT. Next, re-register the workflow service via PowerShell. Finally, Reactivate the workflow feature(s).


text:
Q: how to resend post multipart/form-data form with upload file to different server with node.js (express.js)? I post a form with file (enctype="multipart/form-data") to node.js (express.js framework) and just want to send this same post request like it is just to different server.
what is the best approach in node.js?

A: remove express.bodyParser and try pipes like these:
req.pipe(request('http://host/url/')).pipe(res)

A: You could try it with Mikeal's Request for Node.js (https://github.com/mikeal/request). It would be something like:
app.post('/postproxy', function(req, res, body){
    req.pipe(request.post('http://www.otherserver.com/posthandler',body)).pipe(res);
});

A: Since https://github.com/mikeal/request is deprecated, here is the solution using http module from node:
app.post('/proxy', (request, response, next) => {
  const options = {
    host: 'destination_host',
    port: 'destination_port',
    method: 'post',
    path: '/destination_path',
    headers: request.headers
  };
  request.pipe(http.request(options, (destinationResponse) => {
    destinationResponse.pipe(response);
  }))
    .on('error', (err) => {
      // error handling here
    })
}

In order to proxy files from multipart/form-data I had to use the original request headers.


text:
Q: How to convert this curl to jQuery AJAX POST? curl --request POST \
--url 'https://usX.api.mailchimp.com/3.0/lists/1234/members' \
--user 'username:api_key' \
--header 'content-type: application/json' \
--data '{"email_address":"user@example.com", "status":"pending"}' \
--include

I've above curl and it's working fine when I try to add subscriber to my Mailchimp list.
However, I'm not sure how to convert this curl to working jQuery AJAX POST request since I only know how to pass data to AJAX POST.
Since this curl has --user, --header and --include, I don't know how to build the correct AJAX.
Please help.
$.ajax({
    url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    type: "POST",
    data: {email_address: "user@example.com", status: "pending"},
    // stuck here - what else should I put?
});

A: This has already been answered in the below question.
Converting curl cmd to jQuery $.ajax().
$.ajax({
    url: "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:api_key"));
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: '{"email_address": "user@example.com", "status": "pending"}',
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});

A: Try the following:
$.ajax({
    url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    username:'username',//change this
    password:'api_key',//change this
    type: "POST",
    contentType: "application/json",
    data: {email_address: "user@example.com", status: "pending"},
    success: function(data){
         //your code to process output value from data
    }
});

or using headers
$.ajax({
        url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
        type: "POST",
        headers: {
              'Authorization':'Basic ' + btoa("username:api_key"),
              'Content-Type':'application/json'
        },
        data: {email_address: "user@example.com", status: "pending"},
        success: function(data){
             //your code to process output value from data
        }
    });

A: Here is a question/answer about sending the user/password with jQuery:
How to use Basic Auth with jQuery and AJAX?
Use jQuery's beforeSend callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

You can set the content-type like this:
contentType: "application/json",

--include seems to be an outputting option for curl:
All HTTP replies contain a set of response headers that are normally hidden, use curl's --include (-i) option to display them as well as the rest of the document.


text:
Q: import one git repo to another via TFS import When you create a new repo in TFS there is an option in TFS to import from another git repo.  You can do Github, bitbucket, etc, but it does not work to import from another of my TFS repos. The reason I want to do this is because I have a project that I use as a template.
I've tried using with and without the authentication option
I expect that I should be able to clone directly.  I am on TFS on Prem version 2017.3.

A: I got the same error too, I don't know if it's a bug or expected behavior.
As a workaround, you can manually import the repo:
Clone the source repo to a temporary folder on your computer using the bare option, as shown in the following command line example, and then navigate to the repo's folder. Note that when cloning using the bare option, the folder name includes the .git suffix. In this example, https://github.com/contoso/old-contoso-repo.git is the source repo to be manually imported.
git clone --bare https://github.com/contoso/old-contoso-repo.git
cd old-contoso-repo.git

Create a target repo using TFS 2017 RTM, and make a note of the clone URL. In this example, https://dev.azure.com/contoso-ltd/MyFirstProject/_git/new-contoso-repo is the URL for the new target repo.
Run the following command to copy the source repo to the target repo.
git push --mirror https://dev.azure.com/contoso-ltd/MyFirstProject/_git/new-contoso-repo

If the source repository has LFS objects then fetch them, and copy them from the source repo to the target repo.
git lfs fetch origin --all
git lfs push --all https://dev.azure.com/contoso-ltd/MyFirstProject/_git/new-contoso-repo

Delete the temporary folder by running the following commands.
cd ..
rm -rf old-contoso-repo.git


text:
Q: Youtube Java API. Make YouTubeService without Login I am beginning to learn how to use the Java Youtube API, but I have run into a problem. I am following the tutorials given by Google:
http://code.google.com/apis/youtube/2.0/developers_guide_java.html
The problem is, is that you seem to need a YouTubeService object to make queries. It seems like the only way to make this is with the user logging in. How can I make queries without having the user log in?
    YouTubeService service = new YouTubeService();  //???? How do I make a proper YouTubeService without login. There is no constructor without and parameters.
    String search = "Dubstep";

    try {
        YouTubeQuery query = new YouTubeQuery(new URL("http://gdata.youtube.com/feeds/api/videos"));
        query.setOrderBy(YouTubeQuery.OrderBy.RELEVANCE);
        query.setFullTextQuery(search);
        query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);

        VideoFeed videoFeed = service.query(query, VideoFeed.class);
        printVideoFeed(videoFeed, true);  // Eclipse also doesn't recognize this method.

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

I am really confused by this, and I really need this help.
Thanks!

A: What is your problem? There is a constructor where you can pass your application name:
http://code.google.com/apis/gdata/javadoc/com/google/gdata/client/youtube/YouTubeService.html
Just call this:
YouTubeService service = new YouTubeService("The name of my application");


text:
Q: open mysql on os x backup disk image I have several databases I set up using mamp. Recently, my mac died of old age and I got a new one. Fortunately I have a made of bootable backup of my hard drive every day.  Unfortunately, I cannot boot off of it with my new mac - the image is os x tiger and the new mac won't run tiger, only os x lion.
The upshot is, I have several mysql databases on that backup disk that I need to move to my new machine.  Is there a way of doing this using my current setup running mamp under lion, perhaps open the databases on the backup disk, export the databases and then restarting mamp from the lion databases, and importing what was exported, or something?
Thanks for any ideas!

A: On a mac, your MySQL installation is located in:
/usr/local/mysql/

This is the folder structure:
$ ls -lah /usr/local/mysql/
total 64
drwxr-xr-x  16 root    wheel   544B Nov 13 15:54 .
drwxrwxr-x  27 root    admin   918B Nov 24 11:42 ..
-rw-r--r--   1 root    wheel    18K Nov 13 15:47 COPYING
-rw-r--r--   1 root    wheel   7.2K Nov 13 15:47 INSTALL-BINARY
-rw-r--r--   1 root    wheel   2.5K Nov 13 15:47 README
drwxr-xr-x  46 root    wheel   1.5K Nov 13 15:54 bin
drwxr-xr-x  18 _mysql  wheel   612B Apr 27 13:37 data
drwxr-xr-x   6 root    wheel   204B Nov 13 15:54 docs
drwxr-xr-x  37 root    wheel   1.2K Nov 13 15:54 include
drwxr-xr-x  12 root    wheel   408B Nov 23 08:58 lib
drwxr-xr-x   5 root    wheel   170B Apr 25 06:48 man
drwxr-xr-x  19 root    wheel   646B Nov 23 08:58 mysql-test
drwxr-xr-x   3 root    wheel   102B Nov 13 15:54 scripts
drwxr-xr-x  32 root    wheel   1.1K Nov 13 15:54 share
drwxr-xr-x  28 root    wheel   952B Nov 13 15:54 sql-bench
drwxr-xr-x  16 root    wheel   544B Nov 13 15:54 support-files

You probably want to copy all of it to your local disk, then install MySQL from a disk image (DMG), backup the installed data folder, copy your backed up data folder contents into /usr/local/mysql/data, permission the folder to mysql, start mysqld and do an mysql_upgrade.
install mysql server from DMG... then...
 sudo mv /usr/local/mysql/data /usr/local/mysql/data_ORIG
 sudo cp /mybackupfolder/mysql/data /usr/local/mysql/data
 sudo chown -Rf mysql:wheel /usr/local/mysql/data
 sudo su -
 nohup /usr/local/mysql/bin/mysqld_safe &
 exit
 /usr/local/mysql/bin/mysql_upgrade -u root -p
 # read output

*Note: if you have a my.cnf, mv it to /etc/my.cnf.ORIG before you start mysqld.


text:
Q: How to check if record was changed on db after inserting data? I insert some data from a db.table1 to db.table2 with a cronjob which runs every minutes. But I need to check if any record has changed after data is inserted on table2 because I get some wrong data on this table when data is inserted.
this is crontab function
$data = DB::connection('mysql2')
    ->table('students')
    ->where('status', '=', 'Y')
    ->get();

foreach ($data as $key => $aStudent) {
    // Check if student_id duplicated
    $existing_data_in = DB::table('student')
        ->where("student_id", $aStudent->student_id)
        ->first();

    if (! $existing_data_in) {
        DB::connection('mysql')->table('student')->insert([
            "first_name"        =>$aStudent->first_name,
            "last_name"         =>$aStudent->last_name,
            "age"               =>$aStudent->age,
            "student_id"        =>$aStudent->student_id,
            "created_at"        =>$aStudent->created_at
        ]);
    }
}

Log::info('Success, Data Updated');

Or maybe should I run cronjob rarely? My problem is when some record on table1 are filed with data and when this record goes to table2 are empty on table2. If I check same student_id on table1 is okay but on table2 are saved empty

i have loged my query on cronjob and this is what i get in case i find an empty filed on table 2. So last name on table 1 in this case is filled with really last name but on table 2 is inserted as empty and this is query (what hapend)
[2022-01-19 14:16:17] local.INFO: select `student_id` `first_name`, `last_name`, `age`, `created_at` from `students` where `student_id` = ? limit 1 [421]

// this comes from query where i check for dublicated lines i think
[2022-01-19 14:16:17] local.INFO: select * from `student` where `student_id` = ? limit 1 [421]

[2022-01-19 14:16:17] local.INFO: insert into `student`
(`student_id`, `first_name`, `last_name`, `age`, `created_at`) values
(?, ?, ?, ?, ?)
["421","name","","38","2022-01-19 14:13:35"]

A: If the tables contain created_at and updated_at columns, you can tell if a record has been updated by comparing the two columns.
->whereRaw('created_at != updated_at')->get();

A: You could wrap everything in a transaction to make sure it works as it should.
$data = DB::connection('mysql2')
    ->table('students')
    ->where('status', '=', 'Y')
    ->get();

$dataToInsert = $data->map(function ($item) {
    return [
        'first_name' => $item->first_name,
        'last_name'  => $item->last_name,
        'age'        => $item->age,
        'student_id' => $item->student_id,
        'created_at' => $item->created_at
    ];
})->all();

$columnsToCheck = ['student_id'];
$columnsToUpdate = [];

$conn = DB::connection('mysql');
$conn->beginTransaction();
try {
    $conn->table('student')->upsert($dataToInsert, $columnsToCheck, $columnsToUpdate);
    $conn->commit();
    Log::info('Success');
} catch (\Exception $e) {
    $conn->rollBack();
    Log::error($e);
}

I'm using upsert. You can read more about it here.
https://laravel.com/docs/8.x/queries#upserts


text:
Q: Unable to link css file using constant I am trying to include css file with php so that i have one same path through my sub folders and files as well. This is my code
<link rel="stylesheet" href="<?=ROOT;?>CustomStyles/MyStyles.css">

I have constant root set up before in this way:
define('ROOT', $_SERVER['DOCUMENT_ROOT']);

However this does not work because the result of the link is that after ROOT constant there is the web address of my server.
Can anyone help me please?
Thank you very much.

A: Place your css file in public directory. Example assets/. And link
<link rel="stylesheet" href="//your.site/assets/MyStyles.css">