input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
CSV separated by ';' have semicolons in some of their attributes and can't parse correctly <p>I've been downloading Tweets in the form of a <code>.csv</code> file with the following schema:
<code>
username;date;retweets;favorites;text;geo;mentions;hashtags;permalink
</code></p>
<p>The problem is that some tweets have semi-colons in their text attribute, for example, "I love you babe ;)"</p>
<p>When i'm trying to import this csv to R, i get some records with wrong schema, as can you see here:
<a href="https://i.stack.imgur.com/5Ikgc.png" rel="nofollow"><img src="https://i.stack.imgur.com/5Ikgc.png" alt="imported csv with read.csv"></a></p>
<p>I think this format error is because of the csv parser founding ; in text section and separating the table there, if you understand what i mean.</p>
<p>I've already tried matching with the regex: <code>(;".*)(;)(.*";)</code>
and replacing it with <code>($1)($3)</code> until not more matches are found, but the error continues in the csv parsing.</p>
<p>Any ideas to clean this csv file? Or why the csv parser is working bad?</p>
<p>Thanks for reading </p>
<p>Edit1:
I think that there is no problem in the structure more than a bad chosen separator (';'), look at these example record</p>
<p><code>
Juan_Levas;2015-09-14 19:59;0;2;"Me sonrieron sus ojos; y me tembló hasta el alma.";MedellÃn,Colombia;;;https://twitter.com/Juan_Levas/status/643574711314710528
</code></p>
<p>This is a well formatted record, but i think that the semi-colon in the text section (Marked between "") forces the parser to divide the text-section in 2 columns, in this case: <code>"Me sonrieron sus ojos</code> and <code>y me tembló hasta el alma.";</code>.
Is this possible?</p>
<p>Also, i'm using <code>read.csv("data.csv", sep=';')</code> to parse the csv to a data-frame.</p>
<p>Edit2:
How to reproduce the error:</p>
<ol>
<li>Get the <code>csv</code> from here [~2 MB]: <a href="http://www.cec.uchile.cl/~vicente.oyanedel/twit_data.csv" rel="nofollow">Download csv</a></li>
<li>Do <code>df <- read.csv('twit_data.csv', sep=';')</code></li>
<li>Explore the resulting DataFrame (You can sort it by Date, Retweets or Favorites and you will see the inconsistences in the parsing)</li>
</ol>
| <p>Your CSV file is not properly formatted: the problem is not the separator occurring in character fields, it's rather the fact that the <code>"</code> are not escaped.</p>
<p>The best thing to do would be to generate a new file with a proper format (typically: using <a href="https://tools.ietf.org/html/rfc4180" rel="nofollow" title="RFC 4180">RFC 4180</a>).</p>
<p>If it's not possible, your best option is to use a "smart" tool like <code>readr</code>:</p>
<pre><code>library(readr)
df <- read_csv2('twit_data.csv')
</code></pre>
<p>It does quite a good job on your file. (I can't see any obvious parsing error in the resulting data frame)</p>
|
Calculate the maximum number of consecutive elements without repetitions in a vector. c++ <p>Hi guys i've to calculate the longest sequence of numbers without any repetitions and return the size of the sub-segment.</p>
<p>The point is that im missing something at some point but I don't know where.</p>
<pre><code>int resolverCaso() {
int num;
int cont = 0;
cin >> num;
int var;
TreeMap<int,int> a;
int aux;
int max = 0;
for (int i = 0; i < num; i++) {
cin >> var;
if (!a.contains(var)) {
a[var] = i;
aux = var;
cont++;
}
else {
if (a[aux]==i-1 && var==aux) {
cont = 1;
a = TreeMap<int, int>();
a[var] = i;
}
else {
a.erase(var);
a[var] = i;
}
}
if (cont > max) {
max = cont;
}
}
return max;
}
</code></pre>
<p>I've tried the following cases with this outputs and everything seems to be ok.</p>
<pre><code> E:1 2 3 1 2 3 O:3
E:2 2 2 2 O:1
E:4 5 6 7 6 O:4
E:7 8 9 10 7 8 9 11 2 O:6
E:7 8 9 10 10 10 1 2 3 4 O:5
E:3 4 2 3 4 2 8 9 10 11 O:7
E:0 O:0 ( empty vector ).
E:1 O:1
</code></pre>
<p>So basically im looking for some sequence that doesn't work with my code.</p>
<p>Thanks.</p>
| <p>The problem is with</p>
<pre><code> else {
a.erase(var);
a[var] = i;
}
</code></pre>
<p>You need to do more here. Try the sequence <code>1 3 4 2 3 4 2 8 9 10 11</code>.</p>
|
How you organize workflow in Jira in game development projects? <p>How to setup workflow in Jira for a game development project.</p>
<p>Following are the tasks in my Project</p>
<ol>
<li>3D modelling</li>
<li>Screenplay writing</li>
<li>Animation</li>
<li>Sound creating </li>
<li>Coloring paper creating</li>
<li>scene stooping </li>
</ol>
<p>What workflow to use or recommend for me ?</p>
| <p>My gut feeling is: you do not need any special workflow.</p>
<p>I would model items 1-6 as Tasks of a User Story/Backlog Item or as Sub-Tasks of a Task: when all are completed the parent is complete also.</p>
|
Haskell split string on last occurence <p>Is there any way I can split String in Haskell on the last occurrence of given character into 2 lists?
For example I want to split list "a b c d e" on space into ("a b c d", "e").
Thank you for answers.</p>
| <p>I'm not sure why the solutions suggested are so complicated. Only <strong><s>one</s> two traversals</strong> are needed:</p>
<pre><code>splitLast :: Eq a => a -> [a] -> Either [a] ([a],[a])
splitLast c' = foldr go (Left [])
where
go c (Right (f,b)) = Right (c:f,b)
go c (Left s) | c' == c = Right ([],s)
| otherwise = Left (c:s)
</code></pre>
<p>Note this is <strong>total</strong> and clearly signifies its failure. When a split is not possible (because the character specified wasn't in the string) it returns a <code>Left</code> with the original list. Otherwise, it returns a <code>Right</code> with the two components.</p>
<pre><code>ghci> splitLast ' ' "hello beautiful world"
Right ("hello beautiful","world")
ghci> splitLast ' ' "nospaceshere!"
Left "nospaceshere!"
</code></pre>
|
Navbar Coding using Bootstrap 3/Responsive Design <p>Hello I have been given two examples when for coding a navbar in bootstrap3. I am not sure what the difference is I know example 1 is fixed and responsive but ex 1 is in a <code><div></code> and ex 2 is set in a header. Confusing as they both work, but which is better. </p>
<p>Example 1</p>
<pre><code> <!-- Fixed navbar -->
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">COMPANY</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="#">Welcome</a></li>
<li><a href="#about">Create</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">lorem<b class="caret"></b></a>
<ul class="dropdown-menu">
<li class="dropdown-header"> lorem</li>
<li class="dropdown-header">lorem</li
<li class="divider"></li>
<li class="dropdown-header">lorem</li>
<li class="dropdown-header">lorem</li>
<li class="divider"></li>
<li class="dropdown-header">lorem</li>
<li class="dropdown-header">lorem</li>
</ul>
</li>
<li><a href="#">Dashboard</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</code></pre>
<p>Example two:</p>
<pre><code><header>
<nav id="header-nav" class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a href="index.html" class="pull-left visible-md visible-lg">
<div id="logo-img"></div>
</a>
<div class="navbar-brand">
<a href="index.html"><h1>David Chu's China Bistro</h1></a>
<p>
<img src="images/star-k-logo.png" alt="Kosher certification">
<span>Kosher Certified</span>
</p>
</div>
</div>
</div>
</nav>
</header>
</code></pre>
| <p>The difference is quite clear. Second snippet of code belongs to a simple Navbar using bootstrap. Whereas the first one is the fixed Navbar that you'd mostly seen on top of websites. It includes dummy navigational data in the form of list items. </p>
<p>You can use online editors like <a href="https://jsfiddle.net/" rel="nofollow">jsfiddle</a> and <a href="https://plnkr.co/" rel="nofollow">plnkr</a> for practicing and viewing results of these examples.</p>
<p>Read more and in detail about bootstrap navbar <a href="http://getbootstrap.com/components/#navbar" rel="nofollow">here</a>.</p>
|
Differences between UINavigationController's Left Edge Swipe and Back Button behaviour <p>I'm trying to figure out the difference between a navigation controller's left edge swipe and back button behavior. I have a bug that only occurs when the you navigate back through a left edge swipe. If you press the back button it works correctly. Nothing custom is being done to enable or disable the back navigation or gesture navigation. </p>
<p>I have found surprisingly few resources on this topic and I'd just like a more thorough understanding of what events are triggered by each, and how behaviourally they are different.</p>
| <p>Does this bug manifest itself all the time, or does it manifest itself if and only if you start a left edge swipe and cancel it? The reason I ask is that we used to write code that assumed that <code>viewWillAppear</code> of the prior VC and <code>viewWillDisappear</code> of the current one would always precede <code>viewDidAppear</code> and <code>viewDidDisappear</code>, respectively. But this is no longer true with interactive transitions, because <code>viewWillAppear</code>/<code>Disappear</code> will be called when you start a transition, but the corresponding <code>viewDidAppear</code>/<code>Disappear</code> may not if the interactive transition is cancelled. In fact, when introducing this concept at WWDC 2013, the presenter joked that they should rename <code>viewWillAppear</code> to "<code>viewMightAppear</code>, or <code>viewWillProbablyAppear</code>, or <code>iReallyWishThisViewWouldAppear</code>".</p>
<p>So, take a look at your <code>viewWillAppear</code> and <code>viewWillDisappear</code> methods and make sure you don't have anything there which is dependent upon the view actually appearing and disappearing, respectively, because if the gesture is canceled, you won't see those events.</p>
<p>For more information, see WWDC 2013 video <a href="https://developer.apple.com/videos/play/wwdc2013/218/" rel="nofollow">Custom Transitions Using View Controllers</a>. Interactive transitions is discussed a little more than half way through the video. It discusses how to implement your own interactive transitions, but the concepts apply to the built-in left-edge swipe of the navigation controller.</p>
<hr>
<p>In a standard "back" button process, popping from the second view controller to the first one, the sequence of events is the typical:</p>
<ul>
<li><code>SecondViewController.viewWillDisappear</code></li>
<li><code>FirstViewController.viewWillAppear</code></li>
<li><code>SecondViewController.viewDidDisappear</code></li>
<li><code>FirstViewController.viewDidAppear</code></li>
</ul>
<p>But if you start a left-edge swipe gesture and pause, the sequence of events is:</p>
<ul>
<li><code>SecondViewController.viewWillDisappear</code></li>
<li><code>FirstViewController.viewWillAppear</code></li>
</ul>
<p>But if you stop the gesture and cancel the transition, rather than seeing the <code>SecondViewController.viewDidDisappear</code> and <code>FirstViewController.viewDidAppear</code>, you will see the following events:</p>
<ul>
<li><code>FirstViewController.viewWillDisappear</code></li>
<li><code>FirstViewController.viewDidDisappear</code></li>
<li><code>SecondViewController.viewWillAppear</code></li>
<li><code>SecondViewController.viewDidAppear</code></li>
</ul>
<p>Depending upon what you're doing in these various "appear" related methods, you can have problems if it's not done correctly. For example, if you're doing some cleanup in <code>viewWillDisappear</code>, make sure you're only cleaning up things that you set up in <code>viewWillAppear</code>. Or if you're doing anything in <code>viewDidAppear</code>, make sure you won't have problems if that method is called again if the interactive transition is cancelled. It's impossible to say what precisely is wrong in your situation without information about what you're doing in these appear-related methods.</p>
<p>But the bottom line is that you just need to make sure that the app isn't making any assumptions that just because a transition started, that it will have necessarily finish.</p>
|
How to validate array(matrix) format? <p>I am making page for array multiplication, and I need to validate array format before action. Textbox should accept only arrays in this format: <code>[[1,2,3],[4,5,6],[7,8,9]]</code> - the matrix array of row arrays.</p>
<p>I tried with regex, but I really can't do it. Is there any other way?</p>
| <p>try the regex given below</p>
<pre><code>^ +\[ ([\[[ +\d+ +,]+ +] +,)+ +\[[ +\d+ ,]+ +] +]$
</code></pre>
<p>all in one final solution...</p>
<p>can manage spaces...</p>
|
Can I build a docker image from an existing database container? <p>I am new to docker. I am using docker compose to manage containers. </p>
<p>My goal is to have a database container persists or not persist data, which can be pulled by other developers without many manual steps (pg_dump and pg_store etc) to run their dev environment locally.</p>
<p>I want to know if I can build a docker image of a snapshot of a database (postgres). Is this possible? If not, what is the recommended way to do this with docker? </p>
<p>Thank you.</p>
| <p>In docker you can save data in two places basically:</p>
<ol>
<li>Inside the container (default)</li>
<li>A volume</li>
</ol>
<p>The database containers are configured to save data in volumes, because in this way the data can survive a container deletion. Also it is faster. When you create an image from a container, the data from volumes won't get into. </p>
<p>But you can create a database container which have an <em>archive</em> script, which will execute <code>pg_dump</code> or <code>cp</code> and save the result in any directory outside any volume mounted. So the data will be inside the container and can fly out to an image.</p>
<p>Then use <code>docker commit <container id></code> to save the changes to a new image. Tag the new image <code>docker tag <image id> registry/postgres:withdata</code> and do a <code>docker push</code>.</p>
<p>In the <code>Dockerfile</code> include a script which after the database startup, check if it is empty. If it is empty restore it using <code>pg_restore</code> or <code>cp</code> from the container.</p>
<p>Well it is only an idea to route you a little. It is possible, just require a little work.</p>
<p>Regards</p>
|
How to run a react app on tomcat <p>I'm trying to run the following example:
<a href="https://github.com/ceolter/ag-grid-react-example" rel="nofollow">https://github.com/ceolter/ag-grid-react-example</a></p>
<p>(ag-grid react example)</p>
<p>But, instead of doing <code>npm run</code> I want to run it on tomcat. How to do it?</p>
| <p>Even though I did not do this with Tomcat I deployed it with IIS. So you can adapt the method to Tomcat.</p>
<ol>
<li>I created an Empty MVC application with a Default Controller and a Default view to get all the MVC magic that Microsoft provides.</li>
<li>I built the React + Redux application with webpack and sent everything into a dist folder that had all the resources needed for the application. Look into how to build a React app with webpack for more details on this.</li>
<li>In the script tag that my main view was delivering I set it to point to the dist folder with all the React code.</li>
<li>I ran the application through the Visual Studio build process and the React code kicked in when the view was served by IIS.</li>
<li>Routing worked as well and Redux dev tools.</li>
</ol>
<p>DefaultController.cs</p>
<pre><code>public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
}
</code></pre>
<p>RouteConfig.cs</p>
<pre><code>public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "",
defaults: new { controller = "Default", action = "Index" }
);
routes.MapMvcAttributeRoutes();
}
}
</code></pre>
<p>Default.cshtml</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Redux Counter Example</title>
</head>
<body>
<div id="root">
</div>
</body>
<script src="~/Scripts/frontend/dist/bundle.js"></script>
</html></code></pre>
</div>
</div>
</p>
|
Using 'if' and 'for' to distinguish between numbers <p>There is a list called "G" and i am trying to replace any numbers above 5 with smile ":)" symbol and any number below 5 with ":(". i wrote this code, and expecting to only have five smiles however, the result is totally different and smile appears for all numbers. Thanks if anyone tell me what's wrong with this very simple and basic code.</p>
<pre><code>`G <- list(1,2,3,4,5,6,7,8,9,10)
B <- for (i in 1:length(G))
if (any(G> 5)) {
print(":)")
} else {
print(":(")
} `
</code></pre>
| <p>The following points will help with the question and understanding of R for the future. </p>
<ol>
<li>Lists vs. Vectors</li>
<li>For loops vs. Vectorization</li>
<li><code>print</code> with assignment</li>
</ol>
<p><strong>Lists</strong></p>
<p>In R, the <code>list</code> object is a special object that can hold other objects. They can hold almost anything, even other lists! Because they are so accepting of a mix of things, they are not equipped with all of the cool functions like vectors.</p>
<p>The vector is a simple R object with a common type. "Common type" means that the entire vector will either be numbers, or character values, or whatever other type we are using. If we created <code>c(1,"a")</code> we will have mixed a letter with a number. These two types will be forced to be only one type, <code>character</code>. The quantitative functions will not work with it anymore. But the list <code>list(1,"a")</code> will hold each as its own type.</p>
<p>In your case, you have a series of whole numbers. When the numbers are in a vector, we can apply many built-in functions to work with them that will not work with the generic list. Functions like <code>sum</code>, <code>mean</code>, and <code>sd</code>, are built to accept vectors. But they do not work with lists. We should change <code>G</code> to a vector:</p>
<pre><code>G <- c(1,2,3,4,5,6,7,8,9,10)
#Or a bit shorter
G <- 1:10
</code></pre>
<p><strong>For loops and Vectorization</strong></p>
<p>In R, because vectors can only be of one type, many cool things are possible. I can do <code>G + 1</code> and R will add one to each element of <code>G</code>. It completed the whole thing without a loop. For conditional statements like yours we can vectorize also:</p>
<pre><code>ifelse(G > 5, ":)", ":(")
</code></pre>
<p><strong>Print with assignment</strong></p>
<p>The <code>print</code> function can be saved but it is better to simply capture the output itself as is:</p>
<pre><code>#Don't do
x <- print("hello")
#Do
x <- "hello"
</code></pre>
<p>Both work, but the second is more in line with R programming. The reason <code>B</code> did not save the output in your case is because you attempted to save the <code>for</code> loop itself. If you would like to save the output of a loop, do it within the loop since the output will be dumped upon completion.</p>
<p>To summarize, we can simplify to:</p>
<pre><code>G <- 1:10
B <- ifelse(G > 5, ":)", ":(")
#[1] ":(" ":(" ":(" ":(" ":(" ":)" ":)" ":)" ":)" ":)"
</code></pre>
|
CSS: Normalizing transparency for overlapping, blended divs <p>Suppose I have divs that represent a person's available times. Different persons' availabilities may overlap. I want to represent this with overlapping colored divs where overlapping regions will sum sensibly, in that regions representing the overlap of ALL persons will always be the same color (hence the term "normalize").</p>
<p>I have two overlapping divs that need to be the same opacity and background color, but the overlapping region's opacity needs to be normalized to 1. This cannot be done with the <code>opacity</code> property, <a href="http://stackoverflow.com/questions/23806048/calculate-sum-opacity-from-layers">since the opacity of the second layer would have to be 1</a>. Can it be done with the <code>mix-blend-mode</code> property, and perhaps modulating the background color as well?</p>
<p><a href="https://i.stack.imgur.com/8E1Rk.png" rel="nofollow"><img src="https://i.stack.imgur.com/8E1Rk.png" alt="enter image description here"></a></p>
<p>If, for instance, there are 3 divs, and all 3 overlapped for some region, that region would need to be the same final color as in the initial scenario (only 2 regions, and those overlapping for some portion).</p>
| <p>you could maybe use absolute positioning and opacity together? so give each div the same opacity and place one div over the other to effectively sum the backgrounds. </p>
<pre><code>.container {
position: relative;
height: 200px;
}
.box {
height: 100px;
width: 100px;
background: #000099;
border: 1px solid #fff;
opacity: 0.5;
}
.two {
position: absolute;
top: 80px;
}
</code></pre>
<p>Something like this <a href="https://jsfiddle.net/fabxnnjx/" rel="nofollow">JsFiddle</a></p>
|
Concatenating multiple lines of a text file together in perl <p>I'm working with some sizable data files - 90012 lines each. Each file contains weather data from 7,501 weather stations for each day of the year. There are 12 lines for each weather station, one for each month. A sample of the data is below (truncated to show only three days for each month).</p>
<p>I would like to write a perl script that concatenates all 12 lines for each weather station onto a single line for easier post processing. Any help is greatly appreciated.</p>
<pre><code>AQW00061705 01 824C 824C 824C
AQW00061705 02 826C 826C 826C
AQW00061705 03 829C 829C 829C
AQW00061705 04 826C 826C 826C
AQW00061705 05 821C 821C 821C
AQW00061705 06 813C 813C 813C
AQW00061705 07 806C 805C 805C
AQW00061705 08 801C 801C 801C
AQW00061705 09 807C 807C 808C
AQW00061705 10 812C 812C 812C
AQW00061705 11 816C 816C 817C
AQW00061705 12 823C 823C 823C
CAW00064757 01 204Q 202Q 200Q
</code></pre>
| <pre><code>perl -ape 'chomp if $. % 12; $G && s/^$G//; $G=$F[0]' file
</code></pre>
<p>Deletes newlines except for every 12th newline. Deletes the first field if it is the same as the first field on the previous line.</p>
<hr>
<p>Earlier suggestion:</p>
<pre><code>perl -pe 'chomp if $. % 12' file
</code></pre>
|
Query sub collection - majority mutual ids that contains in list <p>Consider the following list:</p>
<pre><code>List<long> listOfIDs = new List<long> { 1, 2, 3, 4 };
</code></pre>
<blockquote>
<p>[(Product) 1 Pineapple - (Supplier) Fruit Inc / Marketplace Inc]> </p>
<p>[2 Strawberry - Fruit Inc]> </p>
<p>[3 Coke - Super Drinks Inc / Marketplace Inc]> </p>
<p>[4 Orange Juice - Super Drinks Inc]</p>
</blockquote>
<pre><code>db.Table.Where(a => a.SubTable.All(b => listOfIds.Contains(b.SubTableId)))
</code></pre>
<p>While I've selected Products 1 and 2, I should get only Fruit Inc as a Supplier. When I include Coke into my list, I <strong>don't want to see any supplier anymore</strong> because there is no Supplier that represents these 3 products at the same time.</p>
<p>Expected Outputs Scenarios:</p>
<p>Selected Products: 1, 2
Expected Result: Fruit Inc</p>
<p>1, 3
Marketplace Inc</p>
<p>1, 2, 3
<strong>Empty.</strong></p>
<p>1, 3, 4
<strong>Empty.</strong></p>
<p>3, 4
Super Drinks Inc</p>
| <p>I think I finally got what's the issue.</p>
<p>So you have a two entities with <code>many-to-many</code> relationship like this:</p>
<pre><code>public class Product
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<Supplier> Suppliers { get; set; }
}
public class Supplier
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
</code></pre>
<p>and given a list with product Ids, you want to get the list of suppliers that provide all the products from the list.</p>
<p>There are at least two ways you could do that:</p>
<pre><code>List<long> productIds = ...;
</code></pre>
<p>(A) Similar to your attempt, but switching the roles of <code>All</code> and<code>Contains</code>:</p>
<pre><code>var suppliers = db.Suppliers
.Where(s => productIds.All(id => s.Products.Any(p => p.Id == id)))
.ToList();
</code></pre>
<p>or if you prefer <code>Contains</code> (both generate one and the same SQL):</p>
<pre><code>var suppliers = db.Suppliers
.Where(s => productIds.All(id => s.Products.Select(p => p.Id).Contains(id)))
.ToList();
</code></pre>
<p>(B) Counting the matches:</p>
<pre><code>var suppliers = db.Suppliers
.Where(s => s.Products.Count(p => productIds.Contains(p.Id)) == productIds.Count)
.ToList();
</code></pre>
<p>I can't say which one is better performance wise, but all they produce the desired result and are supported by LINQ to Entities.</p>
|
Ordering an ArrayList with duplicate Strings <p>Well i have an ArrayList with some strings in it
and i want to get the number of duplicates that each string has and order them from the highest number to the lowest like this : </p>
<pre><code>ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
Set<String> uniqueSet = new HashSet<String>(list);
for (String temp : uniqueSet) {
System.out.println(temp + ": " + Collections.frequency(list, temp));
}
</code></pre>
<p>and i want to store the top 10 values for a <strong><em>Charting</em></strong> project so i don't just need to print them, i need to put the result somewhere, that for example when i call "a" it gives me 3.</p>
| <p>To map a string to an int (letter to frequency) you can use a Map object:</p>
<pre><code>ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
Collections.sort(list);
Map<String, Integer> map = new HashMap<String,Integer>();
for (String string : list) {
if(!map.containsKey(string)){
map.put(string, Collections.frequency(list, string));
}
}
</code></pre>
<p>and then the map contains the wanted information.</p>
<p>A HashMap is a convenient way to store information which has unique keys and for each key there's a value.</p>
|
Use dub to output C++ linkable static library <p>I want to statically link my D library (which uses dub) with my C++ app.</p>
<p>I've followed <a href="http://wiki.dlang.org/Building_a_mixed_C%2B%2B_and_D_project" rel="nofollow">the instructions on the wiki</a> to successfully manually link the example.</p>
<p>But, I have my own library that uses dub, and I can't figure out how to make it output something I link to using <code>cl</code>.</p>
<hr>
<p>Let me show you what I mean (example code <a href="http://wiki.dlang.org/Building_a_mixed_C%2B%2B_and_D_project#Examples" rel="nofollow">from the wiki</a>, but with dub added):</p>
<p><strong>Project directory:</strong></p>
<pre><code>E:\Projects\foo
â main.c
â
ââââlibadd
â dub.json
â libadd.lib
â
ââââsource
main.d
</code></pre>
<p><strong>main.c:</strong></p>
<pre><code>#include <stdio.h>
// Defined in dlib.d
int add(int, int);
int main(int argc, char ** argv) {
int result = add(40, 2);
printf("The result is: %i\n", result);
return 0;
}
</code></pre>
<p><strong>libadd/dub.json:</strong></p>
<pre><code>{
"name": "libadd",
"targetType": "staticLibrary",
"mainSourceFile": "libadd.d",
"buildOptions": [
"verbose"
]
}
</code></pre>
<p><strong>libadd/source/libadd.d:</strong></p>
<pre><code>module libadd;
extern (C) int add(int a, int b) {
return a + b;
}
// Only needed on Linux.
extern (C) void _d_dso_registry() {}
</code></pre>
<hr>
<p>Compiling and linking using instructions from the wiki works fine:</p>
<pre><code>e:\Projects\foo> dmd -c -v -m32mscoff -betterC libadd/source/libadd.d
binary C:\opt\D\dmd2\windows\bin\dmd.exe
version v2.071.1
config C:\opt\D\dmd2\windows\bin\sc.ini
parse libadd
importall libadd
import object (C:\opt\D\dmd2\windows\bin\..\..\src\druntime\import\object.d)
semantic libadd
semantic2 libadd
semantic3 libadd
code libadd
function libadd.add
function libadd._d_dso_registry
e:\Projects\foo> cl /nologo /Fefoo.exe main.c libadd.obj
main.c
e:\Projects\foo> foo.exe
The result is: 42
</code></pre>
<p>But how do I do this with dub? I noticed that while manual compiling with <code>dmd</code> produces an <code>.obj</code>, <code>dub</code> produces an <code>.lib</code>. According to professor Google, <code>.lib</code> is a static library on Windows, but I can't link to it. I already set <code>targetType</code> to <code>staticLibrary</code> in <code>dub.json</code>.</p>
<p>I also noticed that the <code>dmd</code> flags <code>-m32mscoff</code> and <code>-betterC</code> have no corresponding <code>buildOptions</code> <a href="https://code.dlang.org/package-format?lang=json#build-options" rel="nofollow">setting in dub.json</a>. I'm not sure how to compensate, though.</p>
<pre><code>e:\Projects\foo> cd libadd
e:\Projects\foo\libadd> dub
Performing "debug" build using dmd for x86.
libadd ~master: building configuration "library"...
binary C:\opt\D\dmd2\windows\bin\dmd.exe
version v2.071.1
config C:\opt\D\dmd2\windows\bin\sc.ini
parse libadd
importall libadd
import object (C:\opt\D\dmd2\windows\bin\..\..\src\druntime\import\object.d)
semantic libadd
semantic2 libadd
semantic3 libadd
code libadd
function libadd.add
function libadd._d_dso_registry
library .dub\build\library-debug-windows-x86-dmd_2071-2DA862E35C1BEDC80780CBC1AB5F7478\libadd.lib
Target is a library. Skipping execution.
e:\Projects\foo\libadd> cd ..
e:\Projects\foo> cl /nologo /Fefoo.exe main.c libadd/libadd.lib
main.c
libadd/libadd.lib : fatal error LNK1136: invalid or corrupt file
</code></pre>
<hr>
<p>How do I statically link my D library that uses dub, with a C++ app?</p>
| <p>After some trouble I figured it out.</p>
<p>It turns out, <code>-m32mscoff</code> is important, and it's required for 32-bit. Compiling and linking for 64-bit works fine as-is.</p>
<p>Add into <code>dub.json</code>:</p>
<pre><code>"dflags-windows-x86-dmd": [
"-m32mscoff"
]
</code></pre>
<p>Even though <code>dub</code> passes <code>-m32</code> to <code>dmd</code>, it's <code>-m32mscoff</code> that's needed. You can now link with <code>cl</code> as normal.</p>
|
How can I Replace using the sql wildcard '%'? <p>So this is the data I am pulling in from powershell (there's actually more, but it all follows the same pattern):</p>
<pre><code>Name : SULESRKMA 1
Location : Leisure Services - Technology Services 2
DriverName : KONICA MINOLTA mc4695MF PS PPD 3
Shared : False 4
ShareName : 5
JobCountSinceLastReset : 0 6
</code></pre>
<p>I am trying to remove 'Name : ' and 'Location : ', and so on, but using the REPLACE command here is part of my sql query:</p>
<pre><code>SELECT * FROM #ReadCmd
WHERE Result LIKE 'Name %:%'
INSERT INTO #output(Name)
SELECT REPLACE(Result, '% %: %', '')
From #ReadCmd
WHERE Result LIKE 'Name %:%'
SELECT * FROM #output
</code></pre>
<p>Or for example, here:</p>
<pre><code>IF OBJECT_ID('tempdb..#fields') != 0
DROP TABLE #fields
CREATE TABLE #fields (Fields varchar(256))
INSERT INTO #fields (Fields)
SELECT REPLACE(Result, ' %: %', '')
FROM #ReadCmd
Where Result Like '% %: %'
</code></pre>
<p>The point is, I'd like to replace the '_________ : ' with nothing, but the REPLACE command reads the sql wild card '%' as an actual percent sign. Is there another way to accomplish this?</p>
<p>Using <code>Select RIGHT(Result,CHARINDEX(': ',Result) -1)</code> outputs in seperate cells:</p>
<pre><code> : SULESRKMA
: PrimoPDF
oft XPS Document Writer
: Fax
: CutePDF Writer
</code></pre>
| <p>you can try </p>
<pre><code>SELECT * FROM #ReadCmd
WHERE Result LIKE '%:%' and Result like 'Name %';
</code></pre>
<p>if you want select only the info after the : then you should use </p>
<pre><code>SUBSTRING(Result, CHARINDEX(':',Result) +2, 255)
from #ReadCmd
WHERE Result LIKE '%:%' and Result like 'Name %';
</code></pre>
|
Extending the page in Django <p>Hi everyone I create my first page extension in Django-cms I save the info buy I can obtain it again</p>
<p>my model is like this</p>
<pre><code>class PageDescriptionExtension(PageExtension):
description_page = models.TextField('description',
default = None,
help_text = 'Please provide a small description about this page',
max_length = 250,
)
image = models.ImageField(upload_to='icons')
extension_pool.register(PageDescriptionExtension)
</code></pre>
<p>my <code>admin.py</code> is this</p>
<pre><code>class PageDescriptionExtensionAdmin(PageExtensionAdmin):
pass
admin.site.register(PageDescriptionExtension, PageDescriptionExtensionAdmin)
</code></pre>
<p>and my toolbar</p>
<pre><code>class PageDescriptionExtensionToolbar(ExtensionToolbar):
# defines the model for the current toolbar
model = PageDescriptionExtension
def populate(self):
# setup the extension toolbar with permissions and sanity checks
current_page_menu = self._setup_extension_toolbar()
# if it's all ok
if current_page_menu:
# retrieves the instance of the current extension (if any) and the toolbar item URL
page_extension, url = self.get_page_extension_admin()
if url:
# adds a toolbar item
current_page_menu.add_modal_item(_('Description page'), url=url,
disabled=not self.toolbar.edit_mode)
</code></pre>
<p>no in my template when I try to bet the element</p>
<pre><code>{% if request.current_page.pagedescriptionextension %}
<img src="{% static request.current_page.pagedescriptionextension.image.url %}">
{% else %}
here
{% endif %}
</code></pre>
<p>this code print <code>here</code> I do this in home page <code>request.current_page</code> return home but <code>request.current_page.pagedescriptionextension</code> don't return anything, any idea about that.</p>
<p>Thank in advance</p>
| <p>To show the page extension in the menus (for example, to enable page icons shown in the menu), you first need to add the icon information to the <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/menus.html" rel="nofollow">navigation node</a>. In the snippet below, I am adding ability to fetch <code>pagemenuiconextension</code>, which is defined very similarly to your page extension. The menu extension needs to be placed in <code>cms_menus.py</code>:</p>
<pre><code>from menus.base import Modifier
from menus.menu_pool import menu_pool
from raven.contrib.django.raven_compat.models import client
from cms.models import Page
class MenuModifier(Modifier):
"""
Injects page object into menus to be able to access page icons
"""
def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb):
# if the menu is not yet cut, don't do anything
if post_cut:
return nodes
for node in nodes:
try:
if "is_page" in node.attr and node.attr["is_page"]:
class LazyPage(object):
id = node.id
page = None
def pagemenuiconextension(self):
try:
if not self.page:
self.page = Page.objects.get(id=self.id)
return self.page.pagemenuiconextension
except AttributeError, ae:
# print ae
return False
except Exception, e:
print e
client.captureException()
node.pageobj = LazyPage()
else:
pass
except Exception, e:
client.captureException()
return nodes
menu_pool.register_modifier(MenuModifier)
</code></pre>
<p>Then you can access it in the menu file (snippet from the corresponding menu item):</p>
<pre><code><div class="{{ child.pageobj.pagemenuiconextension.menu_navicon }}" style="height: 16px;">{{ child.get_menu_title }}</div>
</code></pre>
<p>The page extension looks something like this:</p>
<pre><code>class PageMenuIconExtension(PageExtension):
class Meta:
verbose_name = _("menu and robots settings")
verbose_name_plural = _("menu and robots settings")
menu_navicon = models.CharField(
_("Page icon"),
choices=MENU_ICON_CHOICES,
blank=True,
max_length=50
)
</code></pre>
<p>In my case I am using a dropdown to select a class, not an image itself but the principle is the same if you used any other data.</p>
|
How create a Func<T, bool> when the T is unknown <p>I have an object that his instance is created on runtime like this:</p>
<pre><code>var type = GetTypeFromAssembly(typeName, fullNameSpaceType);
var instanceOfMyType = Activator.CreateInstance(type);
ReadObject(instanceOfMyType.GetType().GetProperties(), instanceOfMyType, fullNameSpaceType);
return instanceOfMyType;
</code></pre>
<p>And I need to find an object by Id, for this I have built the follow method:</p>
<pre><code>var parameter = Expression.Parameter(typeof(object));
var condition =
Expression.Lambda<Func<object, bool>>(
Expression.Equal(
Expression.Property(parameter, theEntity.GetType().GetProperty("Id").Name),
Expression.Constant(id, typeof(TKey))
), parameter
).Compile();
</code></pre>
<p>But throws an unhandled exception that says:</p>
<blockquote>
<p>The instance property 'Id' is not defined for type 'System.Object'</p>
</blockquote>
<p>So, how I can built a Func with T where T is seted on runtime ?? Something like this:</p>
<pre><code>var parameter = Expression.Parameter(typeof(MyObjectReflectionRuntimeType>));
var condition =
Expression.Lambda<Func<MyObjectReflectionRuntimeType, bool>>(
Expression.Equal(
Expression.Property(parameter, theEntity.GetType().GetProperty("Id").Name),
Expression.Constant(id, typeof(TKey))
), parameter
).Compile();
</code></pre>
<p><strong>UPDATE [Solution with out Entity Framework]</strong></p>
<p>I have made the follow:</p>
<pre><code> public interface IBaseObject<T>
{
T Id { get; set; }
}
public class AnyClass : IBaseObject<Guid>
{
public Guid Id { get; set; }
}
var parameter = Expression.Parameter(typeof(IBaseObject<Guid>));
var id = Guid.NewGuid();
var theEntity = new AnyClass();
var theList = new List<AnyClass>
{
new AnyClass
{
Id = Guid.NewGuid()
},
new AnyClass
{
Id = Guid.NewGuid()
},
new AnyClass
{
Id = id
},
new AnyClass
{
Id = Guid.NewGuid()
}
};
var condition =
Expression.Lambda<Func<IBaseObject<Guid>, bool>>(
Expression.Equal(
Expression.Property(parameter, theEntity.GetType().GetProperty("Id").Name),
Expression.Constant(id, typeof(Guid))
), parameter
).Compile();
var theMetaData = theList.Where(condition).FirstOrDefault();
</code></pre>
<p>But it crashes on Entity Framework because the <code>IBaseObject<T></code> its not part of the context :( ...</p>
<p><strong>[UPDATE TWO]</strong></p>
<p>I have find a solution like this but it not optimal (Thanks to @Serge Semenov):</p>
<pre><code> var parameter = Expression.Parameter(typeof(object));
var entity = Expression.Convert(parameter, theEntity.GetType());
var condition =
Expression.Lambda<Func<object, bool>>(
Expression.Equal(
Expression.Property(entity, theEntity.GetType().GetProperty("Id").Name),
Expression.Constant(id, typeof(TKey))
), parameter
).Compile();
var theObject = await _unitOfWork.Set(theEntity.GetType()).ToListAsync();
return theObject.FirstOrDefault(condition);
</code></pre>
<p>I'm say that is not the best way because instead of use <code>await _unitOfWork.Set(theEntity.GetType()).ToListAsync();</code> I would like to use: <code>await _unitOfWork.Set(theEntity.GetType()).FirstOrDefaultAsync();</code> but it does not work ...</p>
<p>Any idea ??</p>
| <p>You pass an <code>object</code> to your <code>Func<></code>, but access the <code>Id</code> property defined on other type.</p>
<p>The easiest fix is to cast the <code>object</code> to a type <code>T</code> and then access its properties, like you would do in C# <code>((T)obj).Id</code>:</p>
<pre><code>var parameter = Expression.Parameter(typeof(object));
var entity = Expression.Convert(parameter, theEntity.GetType());
...
Expression.Property(entity, theEntity.GetType().GetProperty("Id").Name),
...
</code></pre>
|
How to use first/head and rest/tail with Swift? <p>In order to use Swift in a functional style, how should we be dealing with <code>head</code> and <code>tail</code>s of lists? Are <code>Array</code>s and <code>ArraySlice</code>s appropriate (seems like it since an <code>ArraySlice</code> is an efficient mechanism to get sublists)? Is the right mechanism to convert an <code>Array</code> to an <code>ArraySlice</code> and use <code>.first!</code> and <code>.dropFirst()</code> as equivalents for <code>head</code> and <code>tail</code>?</p>
<p>As an example of adding a list of numbers:</p>
<pre><code>func add(_ nums: ArraySlice<Int>) -> Int {
if nums.count == 0 {
return 0
} else {
return nums.first! + add(nums.dropFirst())
}
}
</code></pre>
| <p><a href="https://developer.apple.com/reference/swift/array" rel="nofollow"><code>Array</code></a> has an initializer (<a href="https://developer.apple.com/reference/swift/array/1538750-init" rel="nofollow"><code>init(_:)</code></a>) that can produce an <code>Array</code> from any <a href="https://developer.apple.com/reference/swift/sequence" rel="nofollow"><code>Sequence</code></a>, such as an <a href="https://developer.apple.com/reference/swift/arrayslice" rel="nofollow"><code>ArraySlice</code></a>.</p>
<pre><code>func sum(_ nums: [Int]) -> Int {
guard let head = nums.first else { return 0; } //base case, empty list.
return head + sum(Array(nums.dropFirst()))
}
let input = Array(1...10)
let output = sum(input)
print(output)
</code></pre>
<p>But really, as <a href="http://stackoverflow.com/users/341994/matt">matt</a> said, don't do this. The head/tail approach to programming makes sense in a language that facilitates it well with pattern matching, good compiler optimizations, tail call optimization, etc. Swift's design encourages using <code>reduce</code>. Not only is it shorter and much more readable, but it's also more performant.</p>
<p>For comparison, here's what a typical Swift approach would be to this:</p>
<pre><code>extension Sequence where Iterator.Element: Integer {
func sum() -> Iterator.Element {
return self.reduce(0, +)
}
}
</code></pre>
<ul>
<li>It's simpler and shorter.</li>
<li>It's polymorphic, so it'll work with any <code>Sequence</code>, rather than just being limited to <code>Array</code></li>
<li><p>It's generic over any <code>Integer</code> type, not just <code>Int</code>. So these all work:</p>
<pre><code>print(Array<UInt> (1...10).sum())
print(Array<UInt8> (1...10).sum())
print(Array<UInt16>(1...10).sum())
print(Array<UInt32>(1...10).sum())
print(Array<UInt64>(1...10).sum())
print(Array< Int> (1...10).sum())
print(Array< Int8> (1...10).sum())
print(Array< Int16>(1...10).sum())
print(Array< Int32>(1...10).sum())
print(Array< Int64>(1...10).sum())
</code></pre></li>
</ul>
<p>However, if you insist on taking this head/tail approach, try this:</p>
<pre><code>extension Array {
func HeadTail<ReturnType>(_ closure: (Element?, [Element]) -> ReturnType) -> ReturnType {
return closure(self.first, Array(self.dropFirst()))
}
}
func sum(_ nums: [Int]) -> Int {
return nums.HeadTail { head, tail in
guard let head = head else { return 0 } //base case, empty list
return head + sum(tail)
}
}
print(sum(Array(1...10)))
</code></pre>
<p><code>HeadTail(_:)</code> abstracts away the details of how the list is split into it's head tail, letting you write <code>sum</code> by only worrying about the <code>head</code> and <code>tail</code> that are provided for you.</p>
|
java multi-thread acquire lock not working <p>I'm trying to write a small snippet of code to lock and unlock a block of code.
the acquire_lock and release_lock functions are as below:</p>
<pre><code> public static void acquire_lock(long timestamp) {
synchronized(operations) {
// put the timestamp into queue
operations.add(timestamp);
// check if the head of queue is current timestamp, if not,
// this means there are some other operations ahead of current one
// so current operation has to wait
while (operations.peek() != timestamp) {
try {
operations.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void release_lock() {
synchronized(operations) {
// poll the finished operation out of queue
// and wake up all waiting operations
operations.poll();
operations.notifyAll();
}
}
</code></pre>
<p>But when I put this code into a test environment, it doesn't always work well,
the whole test code is as below:</p>
<pre><code>public class AcquireLockNotWork {
static int balance = 0;
static PriorityQueue<Long> operations = new PriorityQueue<Long>();
// withdraw money from balance
public static void withdraw(final int amt) {
// get system time
Long timestamp = System.nanoTime();
Thread t = new Thread(new Runnable() {
public void run() {
// try to use acquire_lock to lock this piece of code
acquire_lock(timestamp);
try {
Thread.sleep(500);
int holdings = balance;
balance = holdings - amt;
System.out.println("Withdrew " + amt + " from funds. Now at " + balance);
} catch (Exception e) {
e.printStackTrace();
} finally {
release_lock();
}
}
});
t.start();
}
//put money into banlance
public static void deposit(int amt) {
Thread t1 = new Thread(new Runnable() {
public void run() {
Long timestamp = System.nanoTime();
acquire_lock(timestamp);
int holdings = balance;
balance = holdings + amt;
System.out.println("deposit " + amt + ", balance: " + balance);
release_lock();
}
});
t1.start();
}
public static void acquire_lock(long timestamp) {
synchronized(operations) {
// put the timestamp into queue
operations.add(timestamp);
// check if the head of queue is current timestamp, if not,
// this means there are some other operations ahead of current one
// so current operation has to wait
while (operations.peek() != timestamp) {
try {
operations.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void release_lock() {
synchronized(operations) {
// poll the finished operation out of queue
// and wake up all waiting operations
operations.poll();
operations.notifyAll();
}
}
public static void test1() {
balance = 0;
deposit(2000);
withdraw(500);
withdraw(1000);
}
public static void main(String[] args) {
test1();
}
}
</code></pre>
<p>for a small number of times, the result will be like this:</p>
<pre><code>deposit 2000, balance: 2000
Withdrew 500 from funds. Now at 500
Withdrew 1000 from funds. Now at 500
</code></pre>
<p>which means that the acquire_lock and release_lock function doesn't work well. It seems that the last two thread (withdrew 500 and withdrew 1000) has entered the block between acquire_lock() and release_lock() simultaneously, and it is not what I want.
So what's wrong with the acquire_lock and release_lock function?</p>
| <p>It is very tricky here.
The anomalous happens because the latter thread enter the acquire_lock first. And when the earlier thread goes into the acquire_lock, it will not be blocked, because the code block the threads based on their timestamp. So the two thread go to the same <em>protected</em> code area. </p>
|
Python expected an indented block on sublime text 3 <p>This is an example excerpt from a bigger code, I have no idea why is this not properly idented</p>
<p>Code example :</p>
<pre><code>if True:
for i in range(1, 10):
print(i)
print("Inside the if")
print("But outside the loop")
</code></pre>
<p>Actual code :</p>
<pre><code>def mkfolder(self):
path = self.edit_dir.text()
prefix,fromn,ton,formatn
if not os.path.isdir(path):
return self.showerror("Erro de parâmetro", "Caminho para criar as pastas é inválido ou não existe\nCód.: 0052")
if not self.chk_prefix.isChecked():
prefix = ""
else:
prefix = self.edit_prefix.text()
if self.chk_count.isChecked():
fromn = self.spin_from.getValue()
ton = self.spin_to.getValue()
formatn = self.spin_format.getValue()
if ton <= fromn:
return self.showerror("Erro de parâmetro", "Não é possÃvel fazer uma contagem regressiva\nCód.: 0010")
if len(str(abs(ton))) < formatn:
return self.showerror("Erro de parâmetro", "Quantidade de dÃgitos é insuficiente\nCód.: 0012")
strFormat = "{0:0>"+ str(formatn) +"}"
msg = self.askquestion("Aviso", str(ton - fromn) + " pastas\n Em " + path + "\n De '" + prefix + strFormat.format(fromn) + "'\na '"+ pref+ strFormat.format(ton) +"'\n\nConfirma?")
if msg==22:
for i in range(fromn, ton+1):
os.makedirs(path + "/"+ prefix + strFormat.format(i))
self.tomain()
self.mkclean()
</code></pre>
| <p>It is improperly indented because you're mixing tabs and spaces. Don't do that. Python doesn't like it when you do that. Every time you do that, a puppy cries</p>
|
Python Watchdog Measure Time Events <p>I'm trying to implement a module called <a href="https://github.com/gorakhargosh/watchdog" rel="nofollow">Watchdog</a> into a project. I'm looking for a way I can measure time between event calls within Watchdog.</p>
<pre><code>if timebetweenevents == 5 seconds:
dothething()
</code></pre>
<p>Thank you,</p>
<p>Charles</p>
<hr>
<p>Edit:</p>
<p>I'm using Python 3.5.0</p>
<p>Here's what the code I was working on <a href="http://pastebin.com/GvSWxymb" rel="nofollow">LINK</a>.</p>
<p>I can print out the current time of the event, but what is the best way to hold on to the time from the last event and then measure the time between since the last event?</p>
| <p>You can modify your Handler class to have a record of the time of the last call.</p>
<p><strong>init</strong> method just initialises the value to the current time.
You will also need to make the method on_any_event a non static method</p>
<pre><code>class Handler(FileSystemEventHandler):
event_time=0
def __init__(self):
self.event_time=time.time()
def on_any_event(self, event):
now=time.time()
timedelta=now-self.event_time
self.event_time=now
print(timedelta)
</code></pre>
|
remove formula links in excel using c# <p>I am copying worksheet from book1 to book2. The worksheet contains cells with formulas. On worksheet 'sheet1' in book2 the cell contains a link back to <code>book1.sheet1 ='Y:\temp\\[book1.xls]sheet1'!A1</code></p>
<p>My question is how to I strip out the <code>Y:\temp\\[book1.xls]sheet1</code> and just have <code>sheet1!A1</code> ? Basically making book2 the source.</p>
<p>I have tried:</p>
<pre><code> for (int i = 2; i <= numberOfSheets; i++)
{
Worksheet ws = (Worksheet)wbDestination.Sheets[i];
Range r = (Range)ws.UsedRange;
bool success = (bool)r.Replace(
@"'Y:\temp\[book1.xls]sheet1'",
"Sheet1",
XlLookAt.xlWhole,
XlSearchOrder.xlByRows,
false, m, m, m);
}
</code></pre>
<p>This doesn't work and get a message that excel was unable to find any matches.</p>
| <p>Try a verbatim string:</p>
<pre><code>@"'Y:\temp\[book1.xls]sheet1'"
</code></pre>
<p>instead of</p>
<pre><code>"'Y:\temp\[book1.xls]sheet1'"
</code></pre>
<p>In a verbatim string, all those special characters are interpreted literally.</p>
|
Open New Tab with Results from JavaScript function <p>This doesn't work:</p>
<pre><code><a href='javascript:void(0)' target='_blank' onclick='do_stuff()' >Open</a>
</code></pre>
<p>And neither does this</p>
<pre><code><a href='javascript:void(0)' target='_blank'onclick='window.open(do_stuff(), "_blank");' >View</a>
</code></pre>
<p>It might be clear what I am trying to do. I need to open up a new tab with the results of a JavaScript function. Is there another way I can try to do this?</p>
| <p>Open new window (tab) and save it to a variable, then change it's content to your function output:</p>
<pre><code><button onclick="clicked()">Test</button>
<script>
var clicked = function () {
var new_page = window.open();
new_page.document.write("output");
}
</script>
</code></pre>
<p>You can use JS to create divs and change it's content:</p>
<pre><code>new_page.document.getElementById('test').innerHTML = "test";
</code></pre>
|
constexpr and function body = delete: what's the purpose? <p>According to the <a href="http://eel.is/c++draft/dcl.constexpr#3" rel="nofollow">[dcl.constexpr/3]</a>:</p>
<blockquote>
<p>The definition of a constexpr function shall satisfy the following requirements:<br>
[...]<br>
- its function-body shall be = delete, = default, or [...]</p>
</blockquote>
<p>This means that the following class snippet is valid:</p>
<pre><code>struct S {
constexpr void f() = delete;
};
</code></pre>
<p>What's the purpose of having a deleted <code>constexpr</code> function?<br>
What are the benefit of defining it <code>constexpr</code> if any?</p>
<p>I can't figure out any reason, but the fact that maybe it's easier to allow it than to forbid it in the standard.</p>
| <p>This was based on <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1199" rel="nofollow">CWG 1199</a>. Daniel Krügler wrote:</p>
<blockquote>
<p>it could be useful to allow this form in a case where a single piece of code is used in multiple configurations, in some of which the function is <code>constexpr</code> and others deleted; having to update all declarations of the function to remove the constexpr specifier is unnecessarily onerous.</p>
</blockquote>
|
Create a list of object usable in more activity <p>I want to create a list of object that is accessible by more activity.
I thought to create a class with the list of object (not array). I used this...</p>
<pre><code>public class List{
Object object1 = new Object("this", 59, true)
...
}
</code></pre>
<p>And activity</p>
<pre><code>public class ListActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
...
ArrayList<Object> array = new ArrayList<>();
array.add(Object(List.object1));
...}}
</code></pre>
<p>in List.object1 there's the error method call expected.</p>
<p>There's a easier method to storage the objects and more efficient?</p>
| <p>you can store your data in settings like this:
settingsservice:</p>
<pre><code>public class SettingsService {
private static String KEY = Constants.SETTINGS_KEY;
private static Context mContext;
public static SettingsModel settings;
public SettingsService(){
mContext = YourApplicationClass.getApplicationContext();
if(settings == null){
settings = getSettings();
}
}
public static void saveSettings(SettingsModel settings){
if(settings != null){
SharedPreferences.Editor editor = mContext
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
SettingsService.settings = settings;
Gson gson = new Gson();
String jsonSettings = gson.toJson(settings);
editor.putString("settings", jsonSettings );
editor.commit();
}
}
public static void saveSettings(){
if(settings == null){
settings = new SettingsModel();
}
SharedPreferences.Editor editor = mContext
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
Gson gson = new Gson();
String jsonSettings = gson.toJson(settings);
editor.putString("settings", jsonSettings );
editor.commit();
}
private static SettingsModel getSettings() {
SharedPreferences editor = mContext.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
try{
String jsonSettings = editor.getString("settings","settings");
Gson gson = new Gson();
settings = gson.fromJson(jsonSettings, SettingsModel.class);
}catch (Exception e){
settings = new SettingsModel();
}
return settings;
}
}
</code></pre>
<p>create settings model whatever objects you want inside:</p>
<pre><code>public class SettingsModel {
public String email;
public String password;
// anything you need else
}
</code></pre>
<p>then from anywhere in your codes:</p>
<pre><code>SettingsService.settings.email = "your email";
SettingsService.saveSettings();
</code></pre>
<p>also from anywhere in your code:</p>
<pre><code>String myEmail = SettingsService.settings.email;
</code></pre>
<p>also make sure you have in your gradle:</p>
<pre><code>compile 'com.google.code.gson:gson:2.4'
</code></pre>
|
Unable to install sami on laravel 5.2.3 for api documentation <p>I am trying to write documentation for a laravel 5.2.3 project and I intend to use Sami to acheive this. </p>
<p>I followed the the git hub link <a href="https://github.com/FriendsOfPHP/Sami" rel="nofollow">https://github.com/FriendsOfPHP/Sami</a> and I tried to install using composer </p>
<p>composer require sami/sami</p>
<p>But I keep getting the error,</p>
<p>Using version ^3.3 for sami/sami
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.</p>
<p>Problem 1
- Installation request for sami/sami ^3.3 -> satisfiable by sami/sami[v3.3.0].
- Conclusion: remove symfony/console v3.1.5
- Conclusion: don't install symfony/console v3.1.5
- sami/sami v3.3.0 requires symfony/console ~2.1 -> satisfiable by symfony/console[v2.1.0, v2.1.1, v2.1.10, v2.1.11, v2.1.12, v2.1.13, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8, v2.1.9, v2.2.0, v2.2.1, v2.2.10, v2.2.11, v2.2.2, v2.2.3, v2.2.4, v2.2.5, v2.2.6, v2.2.7, v2.2.8, v2.2.9, v2.3.0, v2.3.1, v2.3.10, v2.3.11, v2.3.12, v2.3.13, v2.3.14, v2.3.15, v2.3.16, v2.3.17, v2.3.18, v2.3.19, v2.3.2, v2.3.20, v2.3.21, v2.3.22, v2.3.23, v2.3.24, v2.3.25, v2.3.26, v2.3.27, v2.3.28, v2.3.29, v2.3.3, v2.3.30, v2.3.31, v2.3.32, v2.3.33, v2.3.34, v2.3.35, v2.3.36, v2.3.37, v2.3.38, v2.3.39, v2.3.4, v2.3.40, v2.3.41, v2.3.42, v2.3.5, v2.3.6, v2.3.7, v2.3.8, v2.3.9, v2.4.0, v2.4.1, v2.4.10, v2.4.2, v2.4.3, v2.4.4, v2.4.5, v2.4.6, v2.4.7, v2.4.8, v2.4.9, v2.5.0, v2.5.1, v2.5.10, v2.5.11, v2.5.12, v2.5.2, v2.5.3, v2.5.4, v2.5.5, v2.5.6, v2.5.7, v2.5.8, v2.5.9, v2.6.0, v2.6.1, v2.6.10, v2.6.11, v2.6.12, v2.6.13, v2.6.2, v2.6.3, v2.6.4, v2.6.5, v2.6.6, v2.6.7, v2.6.8, v2.6.9, v2.7.0, v2.7.1, v2.7.10, v2.7.11, v2.7.12, v2.7.13, v2.7.14, v2.7.15, v2.7.16, v2.7.17, v2.7.18, v2.7.19, v2.7.2, v2.7.3, v2.7.4, v2.7.5, v2.7.6, v2.7.7, v2.7.8, v2.7.9, v2.8.0, v2.8.1, v2.8.10, v2.8.11, v2.8.12, v2.8.2, v2.8.3, v2.8.4, v2.8.5, v2.8.6, v2.8.7, v2.8.8, v2.8.9].
- Can only install one of: symfony/console[v2.3.10, v3.1.5].
- Can only install one of: symfony/console[v2.3.11, v3.1.5].
- Can only install one of: symfony/console[v2.3.12, v3.1.5].
- Can only install one of: symfony/console[v2.3.13, v3.1.5].
- Can only install one of: symfony/console[v2.3.14, v3.1.5].
- Can only install one of: symfony/console[v2.3.15, v3.1.5].
- Can only install one of: symfony/console[v2.3.16, v3.1.5].
- Can only install one of: symfony/console[v2.3.17, v3.1.5].
- Can only install one of: symfony/console[v2.3.18, v3.1.5].
- Can only install one of: symfony/console[v2.3.19, v3.1.5].
- Can only install one of: symfony/console[v2.3.20, v3.1.5].
- Can only install one of: symfony/console[v2.3.21, v3.1.5].
- Can only install one of: symfony/console[v2.3.22, v3.1.5].
- Can only install one of: symfony/console[v2.3.23, v3.1.5].
- Can only install one of: symfony/console[v2.3.24, v3.1.5].
- Can only install one of: symfony/console[v2.3.25, v3.1.5].
- Can only install one of: symfony/console[v2.3.26, v3.1.5].
- Can only install one of: symfony/console[v2.3.27, v3.1.5].
- Can only install one of: symfony/console[v2.3.28, v3.1.5].
- Can only install one of: symfony/console[v2.3.29, v3.1.5].
- Can only install one of: symfony/console[v2.3.30, v3.1.5].
- Can only install one of: symfony/console[v2.3.31, v3.1.5].
- Can only install one of: symfony/console[v2.3.32, v3.1.5].
- Can only install one of: symfony/console[v2.3.33, v3.1.5].
- Can only install one of: symfony/console[v2.3.34, v3.1.5].
- Can only install one of: symfony/console[v2.3.35, v3.1.5].
- Can only install one of: symfony/console[v2.3.36, v3.1.5].
- Can only install one of: symfony/console[v2.3.37, v3.1.5].
- Can only install one of: symfony/console[v2.3.38, v3.1.5].
- Can only install one of: symfony/console[v2.3.39, v3.1.5].
- Can only install one of: symfony/console[v2.3.40, v3.1.5].
- Can only install one of: symfony/console[v2.3.41, v3.1.5].
- Can only install one of: symfony/console[v2.3.42, v3.1.5].
- Can only install one of: symfony/console[v2.4.10, v3.1.5].
- Can only install one of: symfony/console[v2.4.2, v3.1.5].
- Can only install one of: symfony/console[v2.4.3, v3.1.5].
- Can only install one of: symfony/console[v2.4.4, v3.1.5].
- Can only install one of: symfony/console[v2.4.5, v3.1.5].
- Can only install one of: symfony/console[v2.4.6, v3.1.5].
- Can only install one of: symfony/console[v2.4.7, v3.1.5].
- Can only install one of: symfony/console[v2.4.8, v3.1.5].
- Can only install one of: symfony/console[v2.4.9, v3.1.5].
- Can only install one of: symfony/console[v2.5.0, v3.1.5].
- Can only install one of: symfony/console[v2.5.1, v3.1.5].
- Can only install one of: symfony/console[v2.5.10, v3.1.5].
- Can only install one of: symfony/console[v2.5.11, v3.1.5].
- Can only install one of: symfony/console[v2.5.12, v3.1.5].
- Can only install one of: symfony/console[v2.5.2, v3.1.5].
- Can only install one of: symfony/console[v2.5.3, v3.1.5].
- Can only install one of: symfony/console[v2.5.4, v3.1.5].
- Can only install one of: symfony/console[v2.5.5, v3.1.5].
- Can only install one of: symfony/console[v2.5.6, v3.1.5].
- Can only install one of: symfony/console[v2.5.7, v3.1.5].
- Can only install one of: symfony/console[v2.5.8, v3.1.5].
- Can only install one of: symfony/console[v2.5.9, v3.1.5].
- Can only install one of: symfony/console[v2.6.0, v3.1.5].
- Can only install one of: symfony/console[v2.6.1, v3.1.5].
- Can only install one of: symfony/console[v2.6.10, v3.1.5].
- Can only install one of: symfony/console[v2.6.11, v3.1.5].
- Can only install one of: symfony/console[v2.6.12, v3.1.5].
- Can only install one of: symfony/console[v2.6.13, v3.1.5].
- Can only install one of: symfony/console[v2.6.2, v3.1.5].
- Can only install one of: symfony/console[v2.6.3, v3.1.5].
- Can only install one of: symfony/console[v2.6.4, v3.1.5].
- Can only install one of: symfony/console[v2.6.5, v3.1.5].
- Can only install one of: symfony/console[v2.6.6, v3.1.5].
- Can only install one of: symfony/console[v2.6.7, v3.1.5].
- Can only install one of: symfony/console[v2.6.8, v3.1.5].
- Can only install one of: symfony/console[v2.6.9, v3.1.5].
- Can only install one of: symfony/console[v2.7.0, v3.1.5].
- Can only install one of: symfony/console[v2.7.1, v3.1.5].
- Can only install one of: symfony/console[v2.7.10, v3.1.5].
- Can only install one of: symfony/console[v2.7.11, v3.1.5].
- Can only install one of: symfony/console[v2.7.12, v3.1.5].
- Can only install one of: symfony/console[v2.7.13, v3.1.5].
- Can only install one of: symfony/console[v2.7.14, v3.1.5].
- Can only install one of: symfony/console[v2.7.15, v3.1.5].
- Can only install one of: symfony/console[v2.7.16, v3.1.5].
- Can only install one of: symfony/console[v2.7.17, v3.1.5].
- Can only install one of: symfony/console[v2.7.18, v3.1.5].
- Can only install one of: symfony/console[v2.7.19, v3.1.5].
- Can only install one of: symfony/console[v2.7.2, v3.1.5].
- Can only install one of: symfony/console[v2.7.3, v3.1.5].
- Can only install one of: symfony/console[v2.7.4, v3.1.5].
- Can only install one of: symfony/console[v2.7.5, v3.1.5].
- Can only install one of: symfony/console[v2.7.6, v3.1.5].
- Can only install one of: symfony/console[v2.7.7, v3.1.5].
- Can only install one of: symfony/console[v2.7.8, v3.1.5].
- Can only install one of: symfony/console[v2.7.9, v3.1.5].
- Can only install one of: symfony/console[v2.8.0, v3.1.5].
- Can only install one of: symfony/console[v2.8.1, v3.1.5].
- Can only install one of: symfony/console[v2.8.10, v3.1.5].
- Can only install one of: symfony/console[v2.8.11, v3.1.5].
- Can only install one of: symfony/console[v2.8.12, v3.1.5].
- Can only install one of: symfony/console[v2.8.2, v3.1.5].
- Can only install one of: symfony/console[v2.8.3, v3.1.5].
- Can only install one of: symfony/console[v2.8.4, v3.1.5].
- Can only install one of: symfony/console[v2.8.5, v3.1.5].
- Can only install one of: symfony/console[v2.8.6, v3.1.5].
- Can only install one of: symfony/console[v2.8.7, v3.1.5].
- Can only install one of: symfony/console[v2.8.8, v3.1.5].
- Can only install one of: symfony/console[v2.8.9, v3.1.5].
- Can only install one of: symfony/console[v2.1.0, v3.1.5].
- Can only install one of: symfony/console[v2.1.1, v3.1.5].
- Can only install one of: symfony/console[v2.1.10, v3.1.5].
- Can only install one of: symfony/console[v2.1.11, v3.1.5].
- Can only install one of: symfony/console[v2.1.12, v3.1.5].
- Can only install one of: symfony/console[v2.1.13, v3.1.5].
- Can only install one of: symfony/console[v2.1.2, v3.1.5].
- Can only install one of: symfony/console[v2.1.3, v3.1.5].
- Can only install one of: symfony/console[v2.1.4, v3.1.5].
- Can only install one of: symfony/console[v2.1.5, v3.1.5].
- Can only install one of: symfony/console[v2.1.6, v3.1.5].
- Can only install one of: symfony/console[v2.1.7, v3.1.5].
- Can only install one of: symfony/console[v2.1.8, v3.1.5].
- Can only install one of: symfony/console[v2.1.9, v3.1.5].
- Can only install one of: symfony/console[v2.2.0, v3.1.5].
- Can only install one of: symfony/console[v2.2.1, v3.1.5].
- Can only install one of: symfony/console[v2.2.10, v3.1.5].
- Can only install one of: symfony/console[v2.2.11, v3.1.5].
- Can only install one of: symfony/console[v2.2.2, v3.1.5].
- Can only install one of: symfony/console[v2.2.3, v3.1.5].
- Can only install one of: symfony/console[v2.2.4, v3.1.5].
- Can only install one of: symfony/console[v2.2.5, v3.1.5].
- Can only install one of: symfony/console[v2.2.6, v3.1.5].
- Can only install one of: symfony/console[v2.2.7, v3.1.5].
- Can only install one of: symfony/console[v2.2.8, v3.1.5].
- Can only install one of: symfony/console[v2.2.9, v3.1.5].
- Can only install one of: symfony/console[v2.3.0, v3.1.5].
- Can only install one of: symfony/console[v2.3.1, v3.1.5].
- Can only install one of: symfony/console[v2.3.2, v3.1.5].
- Can only install one of: symfony/console[v2.3.3, v3.1.5].
- Can only install one of: symfony/console[v2.3.4, v3.1.5].
- Can only install one of: symfony/console[v2.3.5, v3.1.5].
- Can only install one of: symfony/console[v2.3.6, v3.1.5].
- Can only install one of: symfony/console[v2.3.7, v3.1.5].
- Can only install one of: symfony/console[v2.3.8, v3.1.5].
- Can only install one of: symfony/console[v2.3.9, v3.1.5].
- Can only install one of: symfony/console[v2.4.0, v3.1.5].
- Can only install one of: symfony/console[v2.4.1, v3.1.5].
- Installation request for symfony/console (locked at v3.1.5) -> satisfiable by symfony/console[v3.1.5].</p>
<p>Is Sami not compatible with Laravel 5.2.3? Because I also tried adding a lower sympony version(~2.6) but an error was displayed indicating the minimum sympony version for laravel 5.2.3 is 3.1.5.</p>
<p>What should i do?</p>
| <p>Seems that the latest official release v3.3 doesnt support symfony3 components which are used by laravel 5.3.<br>
You can try to install the dev-master branch which supports symfony3.</p>
<pre><code>composer require sami/sami dev-master
</code></pre>
<p>The dev-master branch is under development so it might have some hickups but i would bet it should work.</p>
<p>You could also ask for a release in the repo.</p>
|
log4j2 with 3rd party appenders <p>I'm trying to set up some third party appenders in a java app (which is a web API) - the appenders are libraries which are added as dependencies. This is a maven app, and those libraries are Raven (via Sentry) and Logentries. They accept logs and provide GUIs to view them.</p>
<p>Things work fine locally - when run locally logs throughout the app successfully show up in both Logentries and Sentry. The configuration is successfully found and parsed fine in both environments. My <code>log4j2.xml</code> config and output when starting the server for both environments is included below.</p>
<p>On the staging environment I'm seeing logs which say <code>CLASS_NOT_FOUND</code>, so maybe this is a class path issue? Any ideas?</p>
<p><strong>config</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<configuration status="all">
<properties>
<property name="pattern">%d{hh:mm:ss.sss} [mode=${env:MODE}] [%t] %-5level %logger{36} - %msg%n</property>
</properties>
<appenders>
<console name="console" target="system_out">
<patternlayout pattern="${pattern}"/>
</console>
<raven name="sentry">
<dsn>[dsn_here]</dsn>
<patternlayout pattern="${pattern}"/>
<!--to turn down the noise-->
<!--<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>-->
</raven>
<logentries name="le">
<token>[token_here]</token>
<patternlayout pattern="${pattern}"/>
<!--to turn down the noise-->
<!--<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>-->
</logentries>
</appenders>
<loggers>
<root level="debug">
<appender-ref ref="le"/>
<appender-ref ref="sentry"/>
<appender-ref ref="console"/>
</root>
<logger name="com.amazonaws" level="debug" additivity="false">
<appender-ref ref="console"/>
</logger>
</loggers>
</configuration>
</code></pre>
<p><strong>staging environment output when starting the server</strong></p>
<pre><code>Oct 13 20:21:23 dev-company1 java: 2016-10-13 20:21:23,723 main DEBUG Initializing configuration XmlConfiguration[location=jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml]
Oct 13 20:21:23 dev-company1 java: 2016-10-13 20:21:23,729 main DEBUG Installed script engines
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,282 main DEBUG Oracle Nashorn Version: 1.8.0_101, Language: ECMAScript, Threading: Not Thread Safe, Compile: true, Names: {nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript}
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,283 main DEBUG PluginManager 'Core' found 99 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,283 main DEBUG PluginManager 'Level' found 0 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,285 main ERROR Error processing element raven ([appenders: null]): CLASS_NOT_FOUND
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,286 main ERROR Error processing element logentries ([appenders: null]): CLASS_NOT_FOUND
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,288 main DEBUG No scheduled items
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,289 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,303 main TRACE TypeConverterRegistry initializing.
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,303 main DEBUG PluginManager 'TypeConverter' found 23 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,317 main DEBUG createProperty(name="pattern", value="%d{hh:mm:ss.sss} [mode=dev] [%t] %-5level %logger{36} - %msg%n")
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,317 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,326 main DEBUG configureSubstitutor(={pattern=%d{hh:mm:ss.sss} [mode=dev] [%t] %-5level %logger{36} - %msg%n}, Configuration(jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml))
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,327 main DEBUG PluginManager 'Lookup' found 13 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,328 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,332 main DEBUG PatternLayout$Builder(pattern="%d{hh:mm:ss.sss} [mode=dev] [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", noConsoleNoAnsi="null", header="null", footer="null")
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,332 main DEBUG PluginManager 'Converter' found 41 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,366 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,367 main DEBUG PluginManager 'Converter' found 41 plugins
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,367 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false-2
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,381 main DEBUG ConsoleAppender$Builder(patternlayout(%d{hh:mm:ss.sss} [mode=dev] [%t] %-5level %logger{36} - %msg%n), Filter=null, target="SYSTEM_OUT", name="console", follow="null", direct="null", ignoreExceptions="null")
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,381 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,381 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,382 main DEBUG createAppenders(={console})
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,382 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,383 main DEBUG createAppenderRef(ref="le", level="null", Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,383 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,383 main DEBUG createAppenderRef(ref="sentry", level="null", Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,383 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,384 main DEBUG createAppenderRef(ref="console", level="null", Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,384 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,385 main DEBUG createLogger(additivity="null", level="DEBUG", includeLocation="null", ={le, sentry, console}, ={}, Configuration(jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml), Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,386 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,387 main DEBUG createAppenderRef(ref="console", level="null", Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,387 main DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,390 main DEBUG createLogger(additivity="false", level="DEBUG", name="com.amazonaws", includeLocation="null", ={console}, ={}, Configuration(jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml), Filter=null)
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,391 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,401 main DEBUG createLoggers(={root, com.amazonaws})
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,401 main ERROR Unable to locate appender "le" for logger config "root"
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,401 main ERROR Unable to locate appender "sentry" for logger config "root"
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,402 main DEBUG Configuration XmlConfiguration[location=jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml] initialized
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,402 main DEBUG Starting configuration XmlConfiguration[location=jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml]
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,402 main DEBUG Started configuration XmlConfiguration[location=jar:file:/home/company-dev/app/current/company-server.jar!/log4j2.xml] OK.
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,403 main TRACE Stopping org.apache.logging.log4j.core.config.DefaultConfiguration@531d72ca...
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,403 main TRACE DefaultConfiguration notified 1 ReliabilityStrategies that config will be stopped.
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,403 main TRACE DefaultConfiguration stopping root LoggerConfig.
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,404 main TRACE DefaultConfiguration notifying ReliabilityStrategies that appenders will be stopped.
Oct 13 20:21:24 dev-company1 java: 2016-10-13 20:21:24,404 main TRACE DefaultConfiguration stopping remaining Appenders.
Oct 13 20:21:45 dev-company1 journal: Suppressed 692 messages from /system.slice/company.service
Oct 13 20:21:45 dev-company1 java: 08:21:45.045 [mode=dev] [cluster-ClusterId{value='57ffecc465bab830ccd6f372', description='null'}-dev-mongo2:27017] DEBUG org.mongodb.driver.cluster - Checking status of dev-mongo2:27017
Oct 13 20:21:45 dev-company1 java: 08:21:45.045 [mode=dev] [cluster-ClusterId{value='57ffecc465bab830ccd6f372', description='null'}-dev-mongo2:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to {type=REPLICA_SET, servers=[{address=dev-mongo2:27017, type=REPLICA_SET_PRIMARY, roundTripTime=9.2 ms, state=CONNECTED}, {address=dev-mongo3:27017, type=REPLICA_SET_SECONDARY, roundTripTime=4.4 ms, state=CONNECTED}, {address=dev-mongo4:27017, type=REPLICA_SET_SECONDARY, roundTripTime=1.4 ms, state=CONNECTED}]
</code></pre>
<p><strong>local environment output when starting the server</strong></p>
<pre><code>2016-10-13 16:38:11,696 main DEBUG Initializing configuration XmlConfiguration[location=/Users/justin/dev/company/company-server/target/classes/log4j2.xml]
2016-10-13 16:38:11,725 main DEBUG Installed script engines
2016-10-13 16:38:12,421 main DEBUG Oracle Nashorn Version: 1.8.0_102, Language: ECMAScript, Threading: Not Thread Safe, Compile: true, Names: {nashorn, Nashorn, js, JS, JavaScript, javascript, ECMAScript, ecmascript}
2016-10-13 16:38:12,421 main DEBUG PluginManager 'Core' found 101 plugins
2016-10-13 16:38:12,422 main DEBUG PluginManager 'Level' found 0 plugins
2016-10-13 16:38:12,429 main DEBUG No scheduled items
2016-10-13 16:38:12,431 main DEBUG Building Plugin[name=property, class=org.apache.logging.log4j.core.config.Property].
2016-10-13 16:38:12,448 main TRACE TypeConverterRegistry initializing.
2016-10-13 16:38:12,448 main DEBUG PluginManager 'TypeConverter' found 23 plugins
2016-10-13 16:38:12,468 main DEBUG createProperty(name="pattern", value="%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n")
2016-10-13 16:38:12,469 main DEBUG Building Plugin[name=properties, class=org.apache.logging.log4j.core.config.PropertiesPlugin].
2016-10-13 16:38:12,482 main DEBUG configureSubstitutor(={pattern=%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n}, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml))
2016-10-13 16:38:12,482 main DEBUG PluginManager 'Lookup' found 13 plugins
2016-10-13 16:38:12,483 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2016-10-13 16:38:12,494 main DEBUG PatternLayout$Builder(pattern="%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", noConsoleNoAnsi="null", header="null", footer="null")
2016-10-13 16:38:12,494 main DEBUG PluginManager 'Converter' found 41 plugins
2016-10-13 16:38:12,514 main DEBUG Building Plugin[name=appender, class=org.apache.logging.log4j.core.appender.ConsoleAppender].
2016-10-13 16:38:12,516 main INFO Log4j appears to be running in a Servlet environment, but there's no log4j-web module available. If you want better web container support, please add the log4j-web JAR to your web archive or server lib directory.
2016-10-13 16:38:12,517 main DEBUG PluginManager 'Converter' found 41 plugins
2016-10-13 16:38:12,518 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false-2
2016-10-13 16:38:12,527 main DEBUG ConsoleAppender$Builder(patternlayout(%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n), Filter=null, target="SYSTEM_OUT", name="console", follow="null", direct="null", ignoreExceptions="null")
2016-10-13 16:38:12,528 main DEBUG Starting OutputStreamManager SYSTEM_OUT.false.false
2016-10-13 16:38:12,528 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2016-10-13 16:38:12,530 main DEBUG PatternLayout$Builder(pattern="%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", noConsoleNoAnsi="null", header="null", footer="null")
2016-10-13 16:38:12,530 main DEBUG Building Plugin[name=appender, class=com.getsentry.raven.log4j2.SentryAppender].
2016-10-13 16:38:12,534 main ERROR appender raven has no parameter that matches element patternlayout
2016-10-13 16:38:12,534 main DEBUG createAppender(name="sentry", dsn="https://229c49d166d34562b819422b438db969:808712a3940b4f838d47b148c57d884e@sentry.company2.com/2?options", ravenFactory="null", release="null", environment="null", serverName="null", tags="null", extraTags="null", filters=null)
2016-10-13 16:38:12,535 main DEBUG Building Plugin[name=layout, class=org.apache.logging.log4j.core.layout.PatternLayout].
2016-10-13 16:38:12,535 main DEBUG PatternLayout$Builder(pattern="%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n", PatternSelector=null, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml), Replace=null, charset="null", alwaysWriteExceptions="null", noConsoleNoAnsi="null", header="null", footer="null")
2016-10-13 16:38:12,536 main DEBUG Building Plugin[name=appender, class=com.logentries.log4j2.LogentriesAppender].
2016-10-13 16:38:12,538 main DEBUG createAppender(name="le", token="eb8056e2-f7df-4882-acb1-3048c7006643", key="null", location="null", httpPut="false", ssl="false", debug="false", useDataHub="false", dataHubAddr="null", dataHubPort="0", logHostName="false", hostName="null", logID="null", ignoreExceptions="false", patternlayout(%d{hh:mm:ss.sss} [mode=local] [%t] %-5level %logger{36} - %msg%n), Filters=null)
2016-10-13 16:38:12,540 main DEBUG Starting LogentriesManager le
2016-10-13 16:38:12,542 main DEBUG AsyncLogger created.
2016-10-13 16:38:12,543 main DEBUG Building Plugin[name=appenders, class=org.apache.logging.log4j.core.config.AppendersPlugin].
2016-10-13 16:38:12,543 main DEBUG createAppenders(={console, sentry, le})
2016-10-13 16:38:12,543 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
2016-10-13 16:38:12,544 main DEBUG createAppenderRef(ref="le", level="null", Filter=null)
2016-10-13 16:38:12,544 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
2016-10-13 16:38:12,545 main DEBUG createAppenderRef(ref="sentry", level="null", Filter=null)
2016-10-13 16:38:12,545 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
2016-10-13 16:38:12,545 main DEBUG createAppenderRef(ref="console", level="null", Filter=null)
2016-10-13 16:38:12,546 main DEBUG Building Plugin[name=root, class=org.apache.logging.log4j.core.config.LoggerConfig$RootLogger].
2016-10-13 16:38:12,547 main DEBUG createLogger(additivity="null", level="DEBUG", includeLocation="null", ={le, sentry, console}, ={}, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml), Filter=null)
2016-10-13 16:38:12,549 main DEBUG Building Plugin[name=appender-ref, class=org.apache.logging.log4j.core.config.AppenderRef].
2016-10-13 16:38:12,550 main DEBUG createAppenderRef(ref="console", level="null", Filter=null)
2016-10-13 16:38:12,550 main DEBUG Building Plugin[name=logger, class=org.apache.logging.log4j.core.config.LoggerConfig].
2016-10-13 16:38:12,552 main DEBUG createLogger(additivity="false", level="DEBUG", name="com.amazonaws", includeLocation="null", ={console}, ={}, Configuration(/Users/justin/dev/company/company-server/target/classes/log4j2.xml), Filter=null)
2016-10-13 16:38:12,552 main DEBUG Building Plugin[name=loggers, class=org.apache.logging.log4j.core.config.LoggersPlugin].
2016-10-13 16:38:12,553 main DEBUG createLoggers(={root, com.amazonaws})
2016-10-13 16:38:12,554 main DEBUG Configuration XmlConfiguration[location=/Users/justin/dev/company/company-server/target/classes/log4j2.xml] initialized
2016-10-13 16:38:12,554 main DEBUG Starting configuration XmlConfiguration[location=/Users/justin/dev/company/company-server/target/classes/log4j2.xml]
2016-10-13 16:38:12,555 main DEBUG Started configuration XmlConfiguration[location=/Users/justin/dev/company/company-server/target/classes/log4j2.xml] OK.
2016-10-13 16:38:12,555 main TRACE Stopping org.apache.logging.log4j.core.config.DefaultConfiguration@7d0587f1...
2016-10-13 16:38:12,555 main TRACE DefaultConfiguration notified 1 ReliabilityStrategies that config will be stopped.
2016-10-13 16:38:12,556 main TRACE DefaultConfiguration stopping root LoggerConfig.
2016-10-13 16:38:12,556 main TRACE DefaultConfiguration notifying ReliabilityStrategies that appenders will be stopped.
2016-10-13 16:38:12,556 main TRACE DefaultConfiguration stopping remaining Appenders.
2016-10-13 16:38:12,556 main DEBUG Shutting down OutputStreamManager SYSTEM_OUT.false.false-1
2016-10-13 16:38:12,556 main TRACE DefaultConfiguration stopped 1 remaining Appenders.
2016-10-13 16:38:12,557 main TRACE DefaultConfiguration cleaning Appenders from 1 LoggerConfigs.
2016-10-13 16:38:12,557 main DEBUG Stopped org.apache.logging.log4j.core.config.DefaultConfiguration@7d0587f1 OK
2016-10-13 16:38:12,628 main TRACE Reregistering MBeans after reconfigure. Selector=org.apache.logging.log4j.core.selector.ClassLoaderContextSelector@19c65cdc
2016-10-13 16:38:12,628 main TRACE Reregistering context (1/1): '18b4aac2' org.apache.logging.log4j.core.LoggerContext@74bf1791
2016-10-13 16:38:12,631 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2'
2016-10-13 16:38:12,631 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=StatusLogger'
2016-10-13 16:38:12,632 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=ContextSelector'
2016-10-13 16:38:12,632 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=*'
2016-10-13 16:38:12,633 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=*'
2016-10-13 16:38:12,633 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=AsyncAppenders,name=*'
2016-10-13 16:38:12,633 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=AsyncLoggerRingBuffer'
2016-10-13 16:38:12,634 main TRACE Unregistering but no MBeans found matching 'org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=*,subtype=RingBuffer'
2016-10-13 16:38:12,637 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2
2016-10-13 16:38:12,640 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=StatusLogger
2016-10-13 16:38:12,641 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=ContextSelector
2016-10-13 16:38:12,643 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=
2016-10-13 16:38:12,644 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Loggers,name=com.amazonaws
2016-10-13 16:38:12,646 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=console
2016-10-13 16:38:12,646 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=le
2016-10-13 16:38:12,647 main DEBUG Registering MBean org.apache.logging.log4j2:type=18b4aac2,component=Appenders,name=sentry
2016-10-13 16:38:12,651 main TRACE Using default SystemClock for timestamps.
2016-10-13 16:38:12,652 main TRACE Using DummyNanoClock for nanosecond timestamps.
2016-10-13 16:38:12,653 main DEBUG Reconfiguration complete for context[name=18b4aac2] at URI /Users/justin/dev/company/company-server/target/classes/log4j2.xml (org.apache.logging.log4j.core.LoggerContext@74bf1791) with optional ClassLoader: null
2016-10-13 16:38:12,653 main DEBUG Shutdown hook enabled. Registering a new one.
2016-10-13 16:38:12,655 main DEBUG LoggerContext[name=18b4aac2, org.apache.logging.log4j.core.LoggerContext@74bf1791] started OK.
2016-10-13 16:38:12,679 main ERROR Recursive call to appender sentry
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.RavenFactory - Attempting to find a working Raven factory
2016-10-13 16:38:12,725 main ERROR Recursive call to appender sentry
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.RavenFactory - Attempting to use 'RavenFactory{name='com.getsentry.raven.DefaultRavenFactory'}' as a Raven factory.
2016-10-13 16:38:12,730 main ERROR Recursive call to appender sentry
04:38:12.012 [mode=local] [main] INFO com.getsentry.raven.DefaultRavenFactory - Using an HTTP connection to Sentry.
2016-10-13 16:38:12,866 main ERROR Recursive call to appender sentry
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.Raven - Adding 'com.getsentry.raven.event.helper.HttpEventBuilderHelper@74f5ce22' to the list of builder helpers.
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.Raven - Adding 'com.getsentry.raven.event.helper.ContextBuilderHelper@40238dd0' to the list of builder helpers.
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.RavenFactory - The raven factory 'RavenFactory{name='com.getsentry.raven.DefaultRavenFactory'}' created an instance of Raven.
04:38:12.012 [mode=local] [main] DEBUG com.getsentry.raven.event.EventBuilder$HostnameCache - Updating the hostname cache
04:38:12.012 [mode=local] [main] INFO com.company.server.companyServer - company-server starting
</code></pre>
| <p>Try <code><Configuration packages="com.getsentry.raven.log4j2"></code> somewhere near the top of your log4j2.xml</p>
<p>(posting this for completeness, though Brett answered this in the comments)</p>
|
On double click get the id <p>If I have many divs around page all with different ids and some with same classes.
How can I say on double click anywhere on the page I need to get id or class or anything from element where I double clicked?</p>
<p>Like when I Say:</p>
<pre><code>$('div').dblclick(function(){
var x = $(this).attr('id');
});
</code></pre>
<p>Can I say something like</p>
<pre><code>$('body').dblclick(function(){
var x = $(this).attr('id');
});
</code></pre>
| <p>You can get the event target, which is the element that the event was triggered on, and then get the closest DIV to that</p>
<pre><code>$('body').dblclick(function(e){
var x = $(e.target).closest('div').attr('id');
});
</code></pre>
<p><a href="https://jsfiddle.net/adeneo/goawwtau/" rel="nofollow"><strong>FIDDLE</strong></a></p>
|
Avoid Sitecore Lucene/Solr Indexing of System Folder <p>I just setup my Solr search functionality in Sitecore and it indexed the site. I can do a search and I get back results. Unfortunately, it indexed TOO much, and is returning system specific things such as templates and analytics nodes in teh content tree. I type in things like 'system' it returns to me things in the /system/ folder and elsewhere.</p>
<p>I was able to reduce a lot of it by adding templates to exclude, but I'd rather just tell it to avoid 1 or two specific folders alltogether (the layout folder, the system folder, etc).</p>
<p>Is there a way to do this in the ContentSearch config? If not, how can I do this?</p>
<p>Thanks!</p>
| <p>You can create a custom index and restrict it to just the content you want in that index by setting the <code>root</code> node:</p>
<pre class="lang-xml prettyprint-override"><code><contentSearch>
<configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch">
<indexes hint="list:AddIndex">
<index id="my_custom_index" type="Sitecore.ContentSearch.SolrProvider.SolrSearchIndex, Sitecore.ContentSearch.SolrProvider">
...
<locations hint="list:AddCrawler">
<crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch">
<Database>web</Database>
<Root>/sitecore/content</Root>
</crawler>
</locations>
....
</index>
</indexes>
</configuration>
</contentSearch>
</code></pre>
<p>Note that index <code>id</code> attribute is set to a custom index name and root node is changed to <code>root</code> node. The above was a copy of <code>Sitecore.ContentSearch.Solr.Index.Web.config</code>, you may need to create a similar one for <code>master</code> based on your requirements.</p>
<p>You can find more information about defining your own custom indexes in this blog post: <a href="http://www.mikkelhm.dk/archive/defining-a-custom-index-in-sitecore-7-the-absolute-minimum" rel="nofollow">Defining a custom index in Sitecore 7, the absolute minimum</a></p>
<p>Alternatively, leave the default indexes alone and add a filter to your own search query to restrict the returned results to <code>/sitecore/content</code> only.</p>
|
xsl code does not return all cities <p>The xsl code is just returning one city for each country. Any idea why? Because I was expecting get all the cities for each country. </p>
<p>You can see the code and the result that Im getting:</p>
<p><strong>RESULT</strong></p>
<pre><code><html>
<ul>
<li>United States</li>
<li>LA</li>
<li></li>
</ul>
<ul>
<li>Poland</li>
<li>GdaÅsk</li>
<li></li>
</ul>
</html>
</code></pre>
<p><strong>CODE</strong></p>
<pre><code> <html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
<xsl:for-each select="//nations">
<xsl:for-each select="nation">
<ul>
<li><xsl:value-of select="nationame"/></li>
<li><xsl:value-of select="cities/city/cityname"/></li>
<li><xsl:value-of select="cities/city/population"/></li>
</ul>
</xsl:for-each>
</xsl:for-each>
</html>
<nations>
<nation>
<nationame>United States</nationame>
<cities>
<city>
<cityname>LA</cityname>
<citypopulation>4000000</citypopulation>
</city>
<city>
<cityname>NY</cityname>
<citypopulation>10000000</citypopulation>
</city>
</cities>
</nation>
<nation>
<nationame>Poland</nationame>
<cities>
<city>
<cityname>GdaÅsk</cityname>
<citypopulation>40000</citypopulation>
</city>
<city>
<cityname>PoznaÅ</cityname>
<citypopulation>100000</citypopulation>
</city>
</cities>
</nation>
</nations>
</code></pre>
<p>Someone realizes why is not working?</p>
| <p>In XSLT 1.0, the <code>xsl:value-of</code> instruction returns the string-value of the <strong>first</strong> node in the selected node-set. To get all the values, you need to use (another) <code>xsl:for-each</code>, for example:</p>
<pre><code><html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xsl:version="1.0">
<xsl:for-each select="nations/nation">
<ul>
<li><xsl:value-of select="nationame"/></li>
<xsl:for-each select="cities/city">
<li><xsl:value-of select="cityname"/></li>
</xsl:for-each>
</ul>
</xsl:for-each>
</html>
</code></pre>
|
zsh alias not recognizing : command not found <p>Hellor everybody, i wanted to add an alias in my .zshrc file but please have a look at this i really don't understand </p>
<pre><code>[23:29:36] charvet:~ $ expressvpn
NAME:
expressvpn - ExpressVPN command line interface
USAGE:
expressvpn command [arguments...]
VERSION:
1.1.0 (e822d60)
COMMANDS:
activate Activate account
connect Connect to VPN
disconnect Disconnect from VPN
status Display service information
list, ls List VPN locations
autoconnect Enable / disable auto-connect
protocol Display / change preferred protocol
refresh Refresh VPN clusters
reset Reset VPN account
diagnostics Display connection diagnostics
preferences List user preferences
help, h Shows a list of commands or help for one command
GLOBAL OPTIONS:
--help, -h show help
--version, -v print the version
</code></pre>
<p>Then i wrote in my file .zshrc </p>
<pre><code> alias expressvpn=vpn
</code></pre>
<p>Then in zsh :</p>
<pre><code> [23:29:46] charvet:~ $ source .zshrc
ls='ls --color=tty'
[23:29:52] charvet:~ $ vpn
zsh: command not found: vpn
[23:29:55] charvet:~ $
</code></pre>
<p>I am completely lost, i don't understand. People talk about the white space around the "=" but i haven't any.</p>
| <p>Try <code>alias vpn=expressvpn</code>?</p>
<p>Try <code>help alias</code> for help with alias syntax.</p>
|
Why is the absolute positioned DIV not inheriting the width of parent? <p>Why is the absolute positioned DIV not inheriting the width of its parent? Div has </p>
<pre><code>div {
position: absolute;
top:100px;
}
<html>
<body>
<div>This DIV</div>
</body>
</html>
</code></pre>
<p>In static positioning the DIV takes all available space, in absolute the width of the DIV is as long as the length of its contents. </p>
| <p>Read @DaniP docs link for the answer.</p>
<p>Add style width : inherit for inheriting the width of its parent</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#divParent{
width:300px;
}
#divAbsolute {
position: absolute;
top:100px;
background:red;
width:inherit;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div id="divParent">
<div id="divAbsolute">This DIV</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
Render Chinese characters from encoded CSV <p>I have a CSV file whose fields contain encoding for chinese characters:</p>
<pre><code>example cell value: \u53ef\u7231\u7684\u7cd6\u679c\u5c0f\u5e97
</code></pre>
<p>How can I save this file (as .xlsx or xls) to properly render the characters?</p>
| <p>First I input the data into cell <strong>A1</strong><br>Then use <em>Text-to-Columns</em> to split the data into <strong>B1</strong> through <strong>H1</strong>.</p>
<p>Then in <strong>B2</strong> enter the formula:</p>
<pre><code>=chrr(MID(B1,2,9999))
</code></pre>
<p>and copy across.</p>
<p>This uses this VBA <em>UDF()</em>:</p>
<pre><code>Public Function chrr(s As String) As String
Dim i As Long
i = Application.WorksheetFunction.Hex2Dec(s)
chrr = ChrW(i)
End Function
</code></pre>
<p>This results in:</p>
<p><a href="https://i.stack.imgur.com/gViSf.png" rel="nofollow"><img src="https://i.stack.imgur.com/gViSf.png" alt="enter image description here"></a></p>
<p>Note I pick a font the supports UniCode.<br><br>Then save in a standard Excel format like <strong>.xlsm</strong>. Naturally, if you have many records in the <strong>.csv</strong> file, you would "package" the results differently, pack the characters into a single cell, or store the results in a row or in a column, etc.</p>
<p><em>Please let me know if the characters are proper.</em></p>
|
Android Marquee Wait duration <p>How to make a Marquee TextView wait for a specific time until it starts to scroll horizontally?
Because when I open an Activity it starts straight to scroll. So you have to wait until its back on startposition to read it.</p>
| <p>in the xml i simply added textView like this</p>
<pre><code><TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!, Hello World!, Hello World!, Hello World!, Hello World!, Hello World!, Hello World!, Hello World!"
android:ellipsize="marquee"
android:singleLine="true"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:freezesText="true"
android:maxLines="1"
android:scrollbars="none" />
</code></pre>
<p>then in code (in activity but can be anywhere)</p>
<pre><code>TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
textView.setSingleLine(false);
textView.setMaxLines(1);
}
@Override
protected void onResume() {
super.onResume();
textView.postDelayed(new Runnable() {
@Override
public void run() {
textView.setSingleLine(true);
}
}, 3000);
}
</code></pre>
|
If I add a WHERE 0 = 1 clause, does SQL Server know how to optimize? <p>If I have a query like</p>
<pre><code>SELECT * FROM vwComputationallyComplexQueryThatTakesALongTimeToRun WHERE 0 = 1
</code></pre>
<p>is SQL Server smart enough to see the <code>WHERE 0 = 1</code> and not actually execute the query in the view <code>vwComputationallyComplexQueryThatTakesALongTimeToRun</code>?</p>
| <p>YES, The SQL Server smart enough to see the WHERE 0 = 1 and not actually execute the query in the view.</p>
<p><strong><em>The Logical Processing Order of the SELECT statement</em></strong></p>
<p>is as following:</p>
<pre><code>FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
</code></pre>
<p><strong>Reference</strong> :</p>
<p><a href="https://msdn.microsoft.com/en-us/library/ms189499.aspx" rel="nofollow">SELECT (Transact-SQL)</a></p>
|
Swift: error: use of undeclared type 'T' <p>Swift 3.0 and getting this error, unsure why:</p>
<p>Code:</p>
<pre><code>func rest(_ list: ArraySlice<T>) -> ArraySlice<T> {
return list.dropFirst()
}
</code></pre>
<p>Error:</p>
<pre><code>error: repl.swift:1:48: error: use of undeclared type 'T'
func rest(_ list: ArraySlice<T>) -> ArraySlice<T> {
^
</code></pre>
| <p>You need to specify the generic parameter of <code>ArraySlice</code>, just using as <code>ArraySlice<T></code> does not declare <code>T</code>:</p>
<pre><code>func rest<T>(_ list: ArraySlice<T>) -> ArraySlice<T> {
return list.dropFirst()
}
</code></pre>
<p>Or:</p>
<pre><code>class MyClass<T> {
func rest(_ list: ArraySlice<T>) -> ArraySlice<T> {
return list.dropFirst()
}
}
</code></pre>
|
How to detect when a maximum number is rolled? <p>This question seems like it would be easily answered by just making an if statement for my maximum in the range, BUT please take a second to read before calling me an idiot. I am making a program that lets the user choose between many different dice. I am wondering if there is an easy way to detect when the maximum value is rolled from any of the options without setting if statements for all of the different dice.</p>
<pre><code>def inphandle(choice):
if choice==4:
roll = random.randint(1,4)
elif choice==6:
roll = random.randint(1,6)
elif choice==8:
roll = random.randint(1,8)
elif choice==10:
roll = random.randint(1,10)
elif choice==20:
roll = random.randint(1,20)
return roll
def dice(roll):
min = 0
if roll==1:
print("Min roll! Try again!")
min = min+1
if roll
def mainmenu():
print("Please choose from the following options:")
print("Roll | EXIT")
option = input()
if option=="EXIT" or option=="exit" or option=="Exit"
print("You rolled" + max + "max rolls and " + min + " min rolls! Goodbye!")
def main():
choice = int(input("Please enter a number corresponding to the number of faces on your dice. E.x. 4 for 4-Sided: "))
cont = input("Would you like to roll the dice? Y or N: ")
while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll)
cont = input("Would you like to roll again? Y or N: ")
while cont=="n" or cont=="N":
easteregg()
cont = input("Do I get bunus points now?!?")
main()
</code></pre>
<p>I do have random imported, but this is simply a section of the whole program. I understand if there is no shortcut to this, but I wanted to check before typing it all out since it might not be necessary. </p>
| <p>first change <code>inphandle</code></p>
<pre><code>def inphandle(choice):
return random.randint(1,choice)
</code></pre>
<p>and then change</p>
<pre><code> while cont=="y" or cont=="Y":
roll = inphandle(choice)
dice(roll,choice)
...
def dice(roll,max_val):
if roll == max_val:print "MAX"
elif roll == 1:print "MIN"
</code></pre>
|
applescript to move files in numeric order <p>i started a project for a friend, that involved moving large quantities of files into specific folders. i was using automator as I'm handling the project on my mac, however automator does not have a feature to move section of files that are numbered numerically. for instance i will have files that are say "this file 100" and ill have 100 files like that. and then files that say "That file 50" and ill have 200 files like that. the project is splitting these files into there own folder but in section. so ill need "This file" 1-25 in one folder 26-80 in anther and so on. same is true for the "THAT FILES" but there isn't a pattern just the requirement my friend has asked for.</p>
<p>is there a easy way to write a script that could grab 1-25 or any sequel ordering with the same file name? because moving each file one at a time with automator has been taking to long.</p>
<p>thank you so much in advanced</p>
| <p>I am not sure tu fully understand your naming convention, but overall , yes, with Applescript, you can move files into folders based on names, eventually adding sequence numbers.</p>
<p>Because I am not sure about your requirements, at least, here are some sample of syntax for main operations :</p>
<p>Get list of files with names containing xxx in folder myFolder :</p>
<pre><code>Tell Application "Finder" to set myList to every file of myFolder whose name contains "xxx"
</code></pre>
<p>Then you have to do a repeat / end repeat loop :</p>
<pre><code>Repeat with aFile in myList
-- do something here with aFile : example with name of aFile
end repeat
</code></pre>
<p>In that loop you can extract name, parse it, add a counter,...
To move file to new folder, you must use "move" instruction in a tell "Finder" bloc. Instruction "make" can also be used to create new destination folder based on name or root names of files. You must remember that Applescript commands will give error if same file name already exists in destination folder : Finder is able to add "copy" in the name, but you must do it yourself in Applescript.</p>
<p>Last advice if about the number of files to handle. If that number is not so high (less than few hundreds) Applescript is still OK for speed. If your number of files is much higher, then you must use either shell command or, better, a mix of AS and shell commands. The shell commands can be called from AS with a "do shell script". For instance, getting the list of 1000 files from a folder is time consuming with AS, but much quicker with 'ls' command ! Same for a copy. here is an example of copy using shell 'cp' :</p>
<pre><code>do shell script "cp " & quoted form of (POSIX path of (aFile as string)) & " " & quoted form of (POSIX path of DestFolder) & (quoted form of newFileName)
</code></pre>
<p>Note : "Posix path" converts the AS file path (Users:myName:Documents:File.txt) into shell path (Users/myName/Documents/File.txt)</p>
<p>I hope it helps.</p>
|
how to wrap text while keeping border in CSS <p>so I've created a snippet of layout that I'd like to re-use in various places in my code. JSFiddle with what it looks like normally with the following dom structure: <a href="https://jsfiddle.net/64x9udcr/" rel="nofollow">https://jsfiddle.net/64x9udcr/</a></p>
<pre><code><a class="stamp">
<div class="stamp-left"><span>0023f23f2</span></div>
<div class="stamp-right"><span>The quick brown fox jumped over the lazy dog</span></div>
</a>
</code></pre>
<p>Basicly an identifier on the left, with a description on the right, not too complicated. It's also inline, so it can be included in a line of text like an identifier.
Ex: <img src="http://i.imgur.com/u7TuYmf.png" alt="image"></p>
<p>What I'm having trouble with is getting it to wrap if necessary. The following is an image of what I'd like to happen when wrapping is needed. A would be preferred, but if not possible, then B.
<img src="http://i.imgur.com/PjzvANt.png" alt="image"></p>
<p>Any pointers as to what combination of CSS I should be using?</p>
| <p>Used flex method with few little changes in your code. </p>
<p><a href="https://jsfiddle.net/64x9udcr/2/" rel="nofollow">https://jsfiddle.net/64x9udcr/2/</a></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.label,
.stamp {
border-radius: 0.25em;
color: rgb(255, 255, 255);
display: inline;
font-size: 75%;
font-weight: bold;
line-height: 1;
padding: 0.2em 0.6em 0.3em;
text-align: center;
vertical-align: baseline;
white-space: nowrap;
}
.stamp {
border: 1px solid rgb(218, 218, 218);
color: inherit;
display: inline-block;
font-size: inherit;
font-weight: inherit;
margin-bottom: 0.1em;
padding: 0;
}
.stamp .stamp-left,
.stamp .stamp-right {
display: inline-block;
padding: 0.2em 0.6em;
}
.stamp .stamp-left {
background: rgb(218, 218, 218) none repeat scroll 0 0;
font-family: "courier";
}
.select2-results__option--highlighted .stamp .stamp-left {
color: rgb(51, 122, 183);
}
a.stamp:hover {
border-color: rgb(35, 82, 124);
}
a.stamp:hover .stamp-left {
background-color: rgb(35, 82, 124);
color: rgb(255, 255, 255);
}
a.stamp:hover .stamp-right {
color: rgb(35, 82, 124);
}
.container {
display: flex;
width: 100%;
}
.stamp {
max-width: 100%;
overflow: hidden;
min-width: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>
<a class="stamp">
<div class="stamp-left"><span>0023f23f2</span>
</div>
<div class="stamp-right"><span>The quick brown fox jumped over the lazy dog</span>
</div>
</a>
</div></code></pre>
</div>
</div>
</p>
|
Trouble with StringTokenizer using two lines of text <p>I have a program that is supposed to take a text file specified in the run arguments and print it one word at a time on separate lines. It is supposed to omit any special characters except for dashes (-) and apostrophes (').</p>
<p>I have basically finished the program, except that I can only get it to print the first line of text in the file.</p>
<p>Here is what is in the text file:</p>
<p>This is the first line of the input file. It has
more than one line!</p>
<p>Here are the run arguments I am using:</p>
<p>java A1 A1.txt</p>
<p>Here is my code:</p>
<pre><code>import java.io.*;
import java.util.*;
public class A1
{
public static void main (String [] args) throws IOException
{
if (args.length > 0)
{
String file = (args[2]);
try
{
FileReader fr = new FileReader (file);
BufferedReader br = new BufferedReader(fr);
String s = br.readLine();
int i = 1;
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
br.close();
} catch (IOException e)
{
System.out.println ("The following error occurred " + e);
}
}
}
}
</code></pre>
| <p>You are only calling <code>readLine()</code> once! So you are only reading and parsing through the first line of the input file. The program then ends.</p>
<p>What you want to do is throw that in a while loop and read every line of the file, until you reach the end, like so:</p>
<pre><code>while((s = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
</code></pre>
<p>Basically, what this means is <em>"while there is a next line to be read, do the following with that line".</em></p>
|
Suffix for ordinal indicator <p>Any suggestions for providing the suffix for the numbers?</p>
<p>I'm working on providing the following output for my code:</p>
<p>Example</p>
<p>Enter an integer (1-46): 6
The 6th number in the Fibonacci sequence is: 8</p>
<p>Below is what I have completed thus far:</p>
<pre><code>import java.util.*;
public class Somethingpart2 {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
//Variable Declaration
int number;
long Fibnumber;
Boolean accepted, limit;
//Beginning of user input for the Fibonacci sequence
System.out.print("Enter an integer (1-46): ");
number = kbd.nextInt();
Fibnumber = Math.round(Math.pow((1+Math.sqrt(5))/2, number) / Math.sqrt(5));
accepted = number >= 1 && number <= 46;
limit = number == Fibnumber;
if (accepted) {
do {
System.out.println("The " + number +" number in the Fibonacci sequence is: "+Fibnumber);
//if ())
return;
}
while (limit);
}
else
System.out.println("Not a valid number.");
</code></pre>
<p>I'm thinking where the <code>//if ()</code> is located, I can come up with a way to use <code>.contains</code> or <code>indexOf</code> to help with, for example, if variable number contains 3 as the last digit, then apply "rd" right after the 3. </p>
<p>*******Updated******
The last issue I seem to be running into is the exception numbers: 11, 12 and 13.</p>
<p>How do you go about ensuring 11, 12, and 13 get overlooked within the following if statements below:</p>
<pre><code>public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
//Variable Declaration
int number;
long Fibnumber;
Boolean accepted, limit;
//Beginning of user input for the Fibonacci sequence
System.out.print("Enter an integer (1-46): ");
number = kbd.nextInt();
Fibnumber = Math.round(Math.pow((1+Math.sqrt(5))/2, number) / Math.sqrt(5));
accepted = number >= 1 && number <= 46;
limit = number == Fibnumber;
if (accepted) {
do {
//System.out.println("The " + number +" number in the Fibonacci sequence is: "+Fibnumber);
if (number % 10 == 3 && number % 10 !=13)
System.out.println("The "+ number+"rd number in the Fibonacci sequence is: "+ Fibnumber);
else
if (number % 10 == 2 && number % 10 != 12)
System.out.println("The "+ number+ "nd number in the Fibonacci sequence is: " +Fibnumber);
else
if (number % 10 == 1 && number % 10 != 11)
System.out.println("The "+ number+ "st number in the Fibonacci sequence is: " +Fibnumber);
else
System.out.println("The "+ number+ "th number in the Fibonacci sequence is: " +Fibnumber);
return;
}
while (limit);
}
else
System.out.println("Not a valid number.");
</code></pre>
<p>I thought I was going about it in the correct way. Is it the parentheses I'm messing up? I've just tried different combinations with no success. </p>
| <p>This is what I came up with:</p>
<pre><code>public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
//Variable Declaration
int number;
long Fibnumber;
Boolean accepted, limit;
//Beginning of user input for the Fibonacci sequence
System.out.print("Enter an integer (1-46): ");
number = kbd.nextInt();
System.out.println("");//Provides a space between the two print out statements within the program.
Fibnumber = Math.round(Math.pow((1+Math.sqrt(5))/2, number) / Math.sqrt(5));
accepted = number >= 1 && number <= 46;
limit = number == Fibnumber;
if (accepted) {
do {
if (number % 10 == 3 && number !=13)
System.out.println("The "+ number+"rd number in the Fibonacci sequence is: "+ Fibnumber);
else
if (number % 10 == 2 && number != 12)
System.out.println("The "+ number+ "nd number in the Fibonacci sequence is: " +Fibnumber);
else
if (number % 10 == 1 && number != 11)
System.out.println("The "+ number+ "st number in the Fibonacci sequence is: " +Fibnumber);
else
System.out.println("The "+ number+ "th number in the Fibonacci sequence is: " +Fibnumber);
return;
}
while (limit);
}
else
System.out.println("Not a valid number.");
</code></pre>
|
How to delete an object based on a specific property that is nil <p>I have three models, a parent, child, grandchild. I have been able to save and link the data correctly. Now I would like to be able to delete the child and grandchild objects, when I delete the parent.</p>
<p>The parent has a property of the child and the child has a property of the grandchild.</p>
<p>Example:</p>
<pre><code>class Parent: Object {
dynamic var name = ""
var child = List<Child>
}
class Child: Object {
dynamic var name = ""
dynamic var parent: Parent?
var grandChild = List<GrandChild>
}
class GrandChild: Object {
dynamic var name = ""
dynamic var child: Child?
}
</code></pre>
<p>(This is not my actual code, so if I messed up on anything here please disregard any errors.)</p>
<p>What I would like to do is to delete the parent, which would make the property of 'parent' in the Child object nil. Then I would like to delete the child object if it's parent property is nil. Then do the same for the grandChild. In other words do a cascading deletion of objects.</p>
<p>So, something like:</p>
<p>if the parent property of Object: Child is nil, then delete the Object.</p>
<p>This seems like a simple problem to solve but I can't find a lot of examples of nested data models from Realm on these boards, or I am not asking the questions in the right way to find them.</p>
| <p>There is no support for cascading deletes in Realm currently, so you have to manually remove child instances. You can use <code>LinkingObjects</code> to remove all children before deleting the parent or just query all child instances where <code>parent == nil</code> after parent is deleted and delete them. See more possible solutions here: <a href="https://github.com/realm/realm-cocoa/issues/1186" rel="nofollow">https://github.com/realm/realm-cocoa/issues/1186</a></p>
|
PHP - Why is session still being created? <p>Good day, while doing my project, I did stuck on Login page.</p>
<p>This might be really trivial question or maybe even duplicate, but I can't find any solution online.</p>
<p>For some reason, my php script simply skips my login form and keeps making session and redirecting to index.php.</p>
<p>Here is my php script, for checking if email and password exist in databse:
<pre><code>if(isset($_POST['login'])) {
require 'connect.php';
$email = $_POST['email'];
$password = $_POST['password'];
$select_userdata = "select * from users where password ='$password' AND email = '$email'";
$run_check = mysqli_query($dbconfig, $select_userdata);
$check_user = mysqli_num_rows($run_check);
/**Error part**/
if ($check_user == 0) {
echo "<script>alert('Password or email is incorrect')</script>";
echo "<script>window.open('login.php','_self')</script>";
} else {
$_SESSION['email'] = $email;
echo "<script>alert ('You Have Been Logged in')</script>";
header('Location: index.php');
exit;
}
}
if(isset($_GET['logout'])) {
unset($_SESSION['email']);
}
</code></pre>
<p>For some reason, script does not care, if I have email and password in database or not. It "pretends" that there is such email address and password, and skips to $_SESSION['email'] = $email;</p>
<p>My question is, what am I doing wrong, and how do I fix it?</p>
| <p>Problem is in your logic not your code. $check_user is 0 or more there is no difference for your code. it always reach the <em>$_SESSION['email'] = $email</em>; line.
Try this:</p>
<pre><code><?php
session_start();
include'functions/dbconfig.php';
if(isset($_POST['login'])) {
require 'functions/connect.php';
$email = $_POST['email'];
$password = md5($_POST['password']);
$select_userdata = "select * from users where password ='$password' AND email = '$email'";
$run_check = mysqli_query($dbconfig, $select_userdata);
$check_user = mysqli_num_rows($run_check);
if ($check_user == 0)
{
echo "<script>alert('Password or email is incorrect')</script>";
echo "<script>window.open('login.php','_self')</script>";
}
else
{
$_SESSION['email'] = $email;
echo "<script>alert ('You Have Been Logged in')</script>";
header('Location: index.php');
exit;
}
}
if(isset($_GET['logout'])) {
unset($_SESSION['email']);
}
?>
</code></pre>
|
Golang SSL authentication <p>I have certificate.pem that I use to perform client authentication with a remote server. When I access the server, normally Chrome pops up, asks if I want to use that certificate, I say yes, then I'm authenticated. I'm trying to figure out why it's not sending the certificate with the dialer when I call it programmatically:</p>
<pre><code>type DialerHelper func() (io.ReadWriter, error)
func DialIt(addr string, port uint16, config *tls.Config) (Dialer, error) {
address := fmt.Sprintf("%s:%d", addr, port)
return DialerHelper(func() (io.ReadWriter, error) {
return tls.Dial("tcp", address, config)
}), nil
}
caPool := x509.NewCertPool()
cert, err := ioutil.ReadFile("certificate.pem")
if err != nil {
panic(err)
}
ok := caPool.AppendCertsFromPEM(cert)
if !ok {
panic(ok)
}
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
RootCAs: caPool, }
tlsconfig.BuildNameToCertificate()
DialIt("some.address.com", 443, tlsconfig)
</code></pre>
<p>I keep getting an error from the server saying there is no client certificate supplied. Am I sending the SSL certificate correctly to the remote server? I'm not an expert with SSL.</p>
<p>Edit: this is the functionality I'm trying to replicate: <code>curl -k --cert /home/me/.ssh/certificate.pem</code></p>
| <p>I usually do the following for using a client certificate with http.Client.</p>
<pre><code>cert, err := tls.LoadX509KeyPair(`/path/ClientCert.pem`, `/path/Key.pem`)
tlsconfig := &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
}
</code></pre>
<p>I'm not sure how you should go about splitting your pem file into key and cert though.</p>
<p>Does your pem file contain only the certificate ?
Or does it also contain the key ?
You can know by opening it in a text editor and looking for
<code>-----BEGIN PRIVATE KEY-----</code> AND / OR <code>-----BEGIN CERTIFICATE-----</code></p>
|
Powershell .Replace RegEx <p>RegEx for Replace is kicking my butt. I am trying find: </p>
<blockquote>
<p>value="COM8"/></p>
</blockquote>
<p>in a text file and replace "COM8" with another com port (ie "COM9", "COM13", etc).</p>
<pre><code>(Get-Content 'C:\Path\File.config').Replace('/".*?"', '"COM99"') | Set-Content 'C:\Path\File.config'
</code></pre>
<p>Thank you in advance for any help you can provide.</p>
| <p><code>Get-Content</code> produces a list of strings. <code>Replace()</code> is called on each string via <a href="https://blogs.msdn.microsoft.com/powershell/2012/06/13/new-v3-language-features/" rel="nofollow">member enumeration</a>. Meaning, you're calling the <a href="https://msdn.microsoft.com/en-us/library/fk49wtc1%28v=vs.110%29.aspx" rel="nofollow"><code>String.Replace()</code></a> method, not the <a href="https://msdn.microsoft.com/en-us/library/xwewhkd1%28v=vs.110%29.aspx" rel="nofollow"><code>Regex.Replace()</code></a> method. The former does only normal string replacements.</p>
<p>Use the <a href="https://technet.microsoft.com/en-us/library/hh847759.aspx" rel="nofollow"><code>-replace</code></a> operator instead:</p>
<pre><code>(Get-Content 'C:\Path\File.config') -replace '=".*?"', '="COM99"' |
Set-Content 'C:\Path\File.config'
</code></pre>
|
How to use mmap in c <p>I've search and I can't seem to find a way on how to use mmap. This is what I have..</p>
<pre><code>char *pchFile;
if ((pchFile = (char *) mmap (NULL, fileSize, PROT_READ, MAP_SHARED, fd, 0)) == (char *) -1){
fprintf(stderr, "Mmap Err: \n");
exit (1);
}
</code></pre>
<p>So, how do I from obtaining pchFile, read from the file? Is pchFile, the array of bytes mapped from mmap? How do I read at an offset like for say 400 bytes? Can I have an offset and read only a certain amount e.g only read 100 bytes?</p>
| <p><code>pchFile</code> is just a plain old <code>char *</code> (with <code>fileSize</code> valid bytes accessible). So if you want a pointer to the data at an offset of 400 bytes, you can just use <code>&pchFile[400]</code> or <code>pchFile + 400</code> for implicit or explicit pointer arithmetic.</p>
<p>How you limit it to 100 bytes is based on the API you're using; C itself has no concept of the "length" of a pointer (there are APIs for NUL-terminated strings, but raw file data isn't likely to have NULs in useful places). For <code>memcpy</code>/<code>memcmp</code> and friends, you'd pass <code>&pchFile[400]</code> as the source, and pass the size as <code>100</code>. For initializing a C++ <code>vector</code>, you'd pass the start and end pointers to the constructor, e.g. <code>std::vector<char> myvec(&pchFile[400], &pchFile[500]);</code>, etc. Usually, it'll either be a start pointer and a length, or a start and end pointer.</p>
|
java programming dead code <p>I just need someone to tell me why index++ is a dead code so I can try to fix it myself. </p>
<p>heres my code for one class </p>
<pre><code>public class ManagementCompany {
private String name;
private String taxID;
private Property[] properties;
private double mgmFeePer;
private final int MAX_PROPERTY = 5;
public ManagementCompany(String name, String taxID, double mgmFee)
{
properties = new Property[MAX_PROPERTY];
this.name = name;
this.taxID = taxID;
this.mgmFeePer = mgmFee;
}
public int getMAX_PROPERTY()
{
return MAX_PROPERTY;
}
public int addProperty(Property property)
{
for(int index = 0; index < properties.length; index++)
{
properties[index] = property;
return (index + 1);
}
return -1;
}
</code></pre>
<p>heres my other class. Not sure if it's needed though</p>
| <p>You have a <code>return</code> in the loop.
By unrolling the for you will see why it is dead code:</p>
<pre><code>FOR INITIALIZATION: int index = 0;
FOR PRE-LOOP CHECK: index < properties.length
FOR BODY EXECUTION: properties[index] = property;
return (index + 1);
FOR POST-LOOP UPDATE: index++
</code></pre>
<p>As you can see, the <code>return</code> makes the loop terminate and exit the <code>for()</code> statement and the enclosing method. This premature termination of the loop is the cause that execution can never reach the post-loop update <code>index++</code>.</p>
<p><strong>EDIT</strong>: I've left this answer incompleted for several hours because the server went under maintenance while I was writing.</p>
|
Git pull before rebasing <p>So I <a href="http://stackoverflow.com/q/40009820/4114128">asked a question yesterday</a> about rebasing in git and got some good answers on what to do. However When I proceeded, I ran into issues that I dont understand 1 bit.</p>
<p>To give a quick overview:</p>
<p>I branched out (<code>Branch2</code>) from another branch - <code>Branch1</code>. <code>Branch1</code> is remote and had a number of commits AFTER I branched from it. All those commits are not squashed. Meanwhile I went about making changes in <code>Branch2</code>. Now Im done with my changes and have to rebase <code>Branch2</code> on top of <code>Branch1</code>.</p>
<p>When I do <code>git status</code> in <code>Branch2</code> it lists all the files that I have changed (which seems right). However when I do a <code>git checkout Branch1</code> and the <code>git status</code> it lists the same files again. I dont understand this, I was under the impression that each branch is like a localized environment and does not show changes to other branches.</p>
<p>Another thing that has my head spinning is that - <code>Branch1</code> has moved forward since I branched out from it. Before rebasing I wanted to update my local copy of <code>Branch1</code> so that my changes in <code>Branch2</code> get rebased on top of the the most recent commits of <code>Branch1</code> so I did <code>git checkout Branch1</code> and <code>git pull</code>. However I got :</p>
<pre><code>error: Your local changes to the following files would be overwritten by merge:
file...
Please, commit your changes or stash them before you can merge.
Aborting
</code></pre>
<p>I dont understand:</p>
<ol>
<li>Why are changes done in <code>branch2</code> showing in <code>git status</code> of <code>Branch1</code>?</li>
<li>If I commit and push my changes on <code>Branch1</code>, then <code>git pull</code>, where will my commit be placed as all the previous commits including the commit where I had branched of of in <code>Branch1</code> have been squashed. </li>
</ol>
| <blockquote>
<p>When I do git status in <code>Branch2</code> it lists all the files that I have changed (which seems right). </p>
</blockquote>
<p>A branch is a pointer to a commit. <code>git status</code> shows the files that are modified but not committed. Maybe it seems right to you but until you commit the changes, checking out a different branch is a risky operation.</p>
<blockquote>
<p>However when I do a <code>git checkout Branch1</code> and the <code>git status</code> it lists the same files again. </p>
</blockquote>
<p>This is because the uncommitted changes are not in a branch and that means they are not in the repository. They are only in the working tree.</p>
<blockquote>
<p>I dont understand this, I was under the impression that each branch is like a localized environment and does not show changes to other branches.</p>
</blockquote>
<p>Your impression is correct.</p>
<blockquote>
<p>Another thing that has my head spinning is that - <code>Branch1</code> has moved forward since I branched out from it.</p>
</blockquote>
<p>Since you didn't create any commit in <code>Branch2</code>, you technically didn't "branched out" from it. <code>Branch2</code> is just a commit in the past of <code>Branch1</code> and not a real branch. Commit your changes on <code>Branch2</code> and it will branch out.</p>
<blockquote>
<p>However I got :</p>
<pre><code>error: Your local changes to the following files would be overwritten by merge:
file...
Please, commit your changes or stash
</code></pre>
</blockquote>
<p>Well, <code>git</code> is trying hard to not destroy your work. It suggests you what to do in order to be safe.</p>
<hr>
<p>If I understood correctly your desire, the commands you have to run are as follows:</p>
<pre><code># go back to Branch2
git checkout Branch2
# commit the changes in Branch2
git add .
git commit
# get the recent commits on Branch1 from the remote server
# there is no need to merge them
git fetch origin
# rebase Branch1 on top of the remote version of Branch1
# git pull produces the same result if you didn't commit anything on Branch1
git rebase origin/Branch1 Branch1
# rebase the commit(s) you created in Branch2 on top of Branch1
git rebase origin/Branch1 Branch2
# now you are on Branch2 and Branch1 is in the past of Branch2
</code></pre>
<p>Good luck!</p>
|
Numbers in the column of the mysql table are not inserting in correct order <p>I am using MySQL Workbench 6.3. I have a table with two columns id and ingredient. But the id values are not getting inserted properly. Check the images for reference. I have tried both below queries</p>
<pre><code>create table ingredients(id int(6) primary key not null, ingredient varchar(30) not null unique);
</code></pre>
<p>and </p>
<pre><code>create table ingredients(id int(6) primary key not null auto_increment, ingredient varchar(30) not null unique);
</code></pre>
<p>But the output is the same.id column values doesnt come in order. Screenshot of id column:</p>
<p><a href="https://i.stack.imgur.com/OZ44P.png" rel="nofollow"><img src="https://i.stack.imgur.com/OZ44P.png" alt="enter image description here"></a></p>
| <p>The order the rows are presented in is arbitrary, though typically it <em>might</em> be in order of insertion. If you want them in some particular order:</p>
<pre><code>SELECT * FROM ingredients ORDER BY id
</code></pre>
|
CSS - "height 100%" scrolls further than the viewport? can i prevent? <p>I'm constructing a preloader for my website. before the site is loaded there is a plain white div on top of everything, that i later fade out to show the content.</p>
<p>i make this div height 100%, but the problem is that this div then gets a nasty scroll - same length as my normal website content is, and im possible to scroll a tall white div while it's loading.</p>
<p>is there any way to make my loading screen div as big as the "viewport" and not having it's as tall as my full website is? and would make it not scrollable?</p>
<p>do i need to hide all my content that is under the loading screen for this to work?</p>
| <p>As Phil mentioned, you could use position absolute (or position fixed). This will take it out of the flow of the rest of the document and won't affect the stuff around it. </p>
<pre><code>.cover {
position:fixed;
top:0;
left:0;
bottom:0;
right:0;
}
</code></pre>
|
Combined Charts in iOS-Chart - Negative values for Line Chart are not rendered <p>I am using io-Charts (<a href="https://github.com/danielgindi/Charts/" rel="nofollow">https://github.com/danielgindi/Charts/</a>).
I will have to show a bar chart and a line chart in the combined chart.
The xAxis will reflect values from -12 to 12 and y value ranges between -3000 to 3000.While the bar diagram is rendered properly for negative y and x axis , the line chart is not showing for values less than 0.As suggested in the following link ,</p>
<p><a href="http://stackoverflow.com/questions/30019464/negative-values-not-displayed-in-line-charts-using-ios-charts-using-swift">Negative values not displayed in line charts using ios-charts using Swift</a></p>
<p>I have set the _chartView.xAxis.axisMinimum = -12; // to start from -12 and not 0.</p>
<p>Please find below the current graph ,
<a href="https://i.stack.imgur.com/5pHBR.png" rel="nofollow"><img src="https://i.stack.imgur.com/5pHBR.png" alt="enter image description here"></a></p>
<p>The Setting for the chart view and data set for the line chart ,</p>
<pre><code> - (LineChartData *)generateLineData
</code></pre>
<p>{
LineChartData *d = [[LineChartData alloc] init];</p>
<pre><code>NSMutableArray *entries = [[NSMutableArray alloc] init];
[entries addObject:[[ChartDataEntry alloc] initWithX:0 y:-3000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:0.5 y:-999]];
[entries addObject:[[ChartDataEntry alloc] initWithX:1 y:-1000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:2 y:-1000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:3.5 y:-1300]];
[entries addObject:[[ChartDataEntry alloc] initWithX:4 y:-900]];
[entries addObject:[[ChartDataEntry alloc] initWithX:5 y:-1200]];
[entries addObject:[[ChartDataEntry alloc] initWithX:6 y:-2500]];
[entries addObject:[[ChartDataEntry alloc] initWithX:8 y:-1300]];
[entries addObject:[[ChartDataEntry alloc] initWithX:9 y:1400]];
[entries addObject:[[ChartDataEntry alloc] initWithX:11 y:-900]];
[entries addObject:[[ChartDataEntry alloc] initWithX:12 y:-3000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-1 y:-1000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-2 y:-1300]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-4 y:-1100]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-5 y:-1500]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-6 y:-1500]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-8 y:-1100]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-9 y:-1000]];
[entries addObject:[[ChartDataEntry alloc] initWithX:-11 y:-1500]];
LineChartDataSet *set = [[LineChartDataSet alloc] initWithValues:entries label:@"Line DataSet"];
[set setColor:[UIColor colorWithRed:240/255.f green:238/255.f blue:70/255.f alpha:1.f]];
set.lineWidth = 2.5;
set.fillColor = [UIColor colorWithRed:240/255.f green:238/255.f blue:70/255.f alpha:1.f];
set.mode = LineChartModeHorizontalBezier;
set.drawValuesEnabled = NO;
set.drawCirclesEnabled = NO;
set.axisDependency = AxisDependencyLeft;
[d addDataSet:set];
return d;
</code></pre>
<p>}</p>
<p>I am not sure if I am missing some setting for the chartview.</p>
| <p>Fixed this by reordering the line chart data set with x values from -12 to 12 , in my original question , the data set was mixed and not in a proper order for the line chart.</p>
|
Using Get-ChildItem to retrieve folder,name,fullname <p>I'm currently using this script to pull the Name,Folder,Foldername from a given path:</p>
<pre><code> Get-ChildItem "C:\user\desktop" | Select Name, `
@{ n = 'Folder'; e = { Convert-Path $_.PSParentPath } }, `
@{ n = 'Foldername'; e = { ($_.PSPath -split '[\\]')[-2] } } ,
@{ n = 'Fullname'; e = { Convert-Path $_.PSParentPath } } |
Export-Csv "C:\user\desktop\txt.txt" -Encoding Utf8 -NoTypeInformation
</code></pre>
<p>I am having trouble getting <code>@{ n = 'Fullname'; e = { Convert-Path $_.PSParentPath } }</code> to pull through the full file path.</p>
<p>Any help greatly appreciated. </p>
| <p><a href="https://msdn.microsoft.com/en-us/library/system.io.directoryinfo%28v=vs.110%29.aspx" rel="nofollow"><code>DirectoryInfo</code></a> objects (the output of <code>Get-ChildItem</code> for folders) have properties <code>Name</code> and <code>FullName</code> with the name and full path of the folder. They also have a property <code>Parent</code> that returns another <code>DirectoryInfo</code> object for the parent folder. You can add that information as a <a href="https://technet.microsoft.com/en-us/library/ff730948.aspx" rel="nofollow">calculated property</a>.</p>
<p>Since you basically want to add the grandparent name and path for the listed items, and that information doesn't change because you don't recurse, you can determine them once and add them as static information:</p>
<pre><code>$dir = 'C:\some\folder'
$folder = (Get-Item $dir).Parent
$folderName = $folder.Name
$folderPath = $folder.FullName
Get-ChildItem $dir |
Select-Object Name, FullName,
@{n='FolderName';e={$folderName}},
@{n='Folder';e={$folderPath}} |
Export-Csv 'C:\path\to\output.csv' -Encoding UTF8 -NoType
</code></pre>
|
Not all Spark Workers are starting: SPARK_WORKER_INSTANCES <p>I have my spark-defaults.conf configuration like this.
my node has 32Gb RAM. 8 cores.
I am planning to use 16gb and 4 workers with each using 1 core.</p>
<pre><code>SPARK_WORKER_MEMORY=16g
SPARK_PUBLIC_DNS=vodip-dt-a4d.ula.comcast.net
SPARK_WORKER_CORES=4
SPARK_WORKER_INSTANCES=4
SPARK_DAEMON_MEMORY=1g
</code></pre>
<p>When i try to start the master and workes like this, only 1 worker is being started where an i am expecting 4 workers.</p>
<pre><code>start-master.sh --properties-file /app/spark/spark-1.6.1-bin-hadoop2.6/conf/ha.conf
start-slaves.sh
</code></pre>
<p>these commands started the master and showed that they were starting 4 workes where as only 1 worker was started.</p>
<p>The one worker that started using all 4 cores.
Please let me know why my other 3 worked are not starting.</p>
| <p>Memory and core properties are for every executor. So when you say SPARK_WORKER_CORES=4 this is every executor with 4 cores.</p>
<p>Also you cant use all memory in your server for executors. If you want 4 executors with total 16gb memory, your properties should be like this</p>
<pre><code>SPARK_WORKER_MEMORY=4g
SPARK_PUBLIC_DNS=vodip-dt-a4d.ula.comcast.net
SPARK_WORKER_CORES=1
SPARK_WORKER_INSTANCES=4
</code></pre>
|
SQL Query: Find the name of the company that has been assigned the highest number of patents <p><img src="https://i.stack.imgur.com/WTqKu.png" alt="Following is the schema of Database"></p>
<p>Using this query I can find the Company Assignee number for company with most patents but I can't seem to print the company name.</p>
<pre><code>SELECT count(*), patent.assignee
FROM Patent
GROUP BY patent.assignee
HAVING count(*) =
(SELECT max(count(*))
FROM Patent
Group by patent.assignee);
</code></pre>
<p>COUNT(*) --- ASSIGNEE</p>
<pre><code> 9 19715
9 27895
</code></pre>
<p>Nesting above query into </p>
<pre><code>SELECT company.compname
FROM company
WHERE ( company.assignee = ( *above query* ) );
</code></pre>
<p>would give an error "too many values" since there are two companies with most patents but above query takes only one assignee number in the WHERE clause. How do I solve this problem? I need to print name of BOTH companies with assignee number 19715 and 27895. Thank you.</p>
| <p>Applying an aggregate function on another aggregate function (like <code>max(count(*))</code>) is illegal in many databases but I believe using the <code>ALL</code> operator instead and a join to get the company name would solve your problem.</p>
<p>Try this:</p>
<pre><code>SELECT COUNT(*), p.assignee, c.compname
FROM Patent p
JOIN Company c ON c.assignee = p.assignee
GROUP BY p.assignee, c.compname
HAVING COUNT(*) >= ALL -- this predicate will return those rows
( -- for which the comparison holds true
SELECT COUNT(*) -- for all instances.
FROM Patent -- it can only be true for the highest count
GROUP BY assignee
);
</code></pre>
|
Ionic (or AngularJS) blocks google maps autocomplete <p>I'm just trying to add a simple autocomplete form to my Ionic app.
So first I tried it <a href="http://jsfiddle.net/GVdK6/265/" rel="nofollow">there</a>, it works perfectly fine.
So I tried in my app (in the browser first).</p>
<p>I put this in my controller, and called it with ng-init="initMaps()"</p>
<pre><code> $scope.initMaps = function() {
var center = new google.maps.LatLng(51.514032, -0.128383);
var circle = new google.maps.Circle({
center: center,
radius: 50
});
var options = {componentRestrictions: {country: 'uk'}, types: ['geocode']}
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setBounds(circle.getBounds());
console.log("maps loaded")
}
</code></pre>
<p>When I look at my console, I can see "maps loaded", and google warnings like: </p>
<blockquote>
<p>Google Maps API warning: SensorNotRequired <a href="https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required" rel="nofollow">https://developers.google.com/maps/documentation/javascript/error-messages#sensor-not-required</a></p>
</blockquote>
<p>I just pu this line in my template form:</p>
<pre><code> <input id="autocomplete" type="text" style="width: 200px;">
</code></pre>
<p>So, I think on a non-ionic (or angular) project it would work fine. But here, when I enter some letters, <strong>I don't get any result</strong></p>
<p>Does Angular/Ionic make interference ? Am I forced to install other modules ?</p>
<p>Thanks !
Robin.</p>
| <p>Since <code>Place Autocomplete</code> is a part of <a href="https://developers.google.com/maps/documentation/javascript/places" rel="nofollow">Google Maps Places Library</a> you probably forgot to include the loading of this library via <code>libraries</code> parameter, for example:</p>
<pre><code><script src="//maps.googleapis.com/maps/api/js?key={KEY}&libraries=places"></script>
</code></pre>
<p><strong>Example</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('ionic.example', ['ionic'])
.controller('MapCtrl', function ($scope) {
$scope.initMap = function () {
var center = new google.maps.LatLng(51.514032, -0.128383);
var circle = new google.maps.Circle({
center: center,
radius: 50
});
var options = { componentRestrictions: { country: 'uk' }, types: ['geocode'] }
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.setBounds(circle.getBounds());
}
google.maps.event.addDomListener(window, 'load', $scope.initMap);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.controls {
margin-top: 10px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script src="//maps.googleapis.com/maps/api/js?libraries=places"></script>
<link href="//code.ionicframework.com/nightly/css/ionic.css" rel="stylesheet">
<script src="//code.ionicframework.com/nightly/js/ionic.bundle.js"></script>
<div ng-app="ionic.example" ng-controller="MapCtrl">
<ion-header-bar class="bar-dark" >
<h1 class="title">Map</h1>
</ion-header-bar>
<ion-content>
<div id="map" data-tap-disabled="true"></div>
<input id="autocomplete" placeholder="Enter your address" class="controls" type="text"></input>
</ion-content>
</div></code></pre>
</div>
</div>
</p>
<p><a href="http://codepen.io/vgrem/pen/zKJGNL" rel="nofollow">Codepen</a></p>
|
Selecting all elements that meet a criteria using selenium (python) <p>Using selenium, is there a way to have the script pick out elements that meet a certain criteria? </p>
<p>What I'm exactly trying to do is have selenium select all Twitch channels that have more than X viewers. If you inspect element, you find this: </p>
<pre><code><p class="info"
562
viewers on
<a class="js-profile-link" href="/hey_jase/profile"
data-tt_content="live_channel" data-tt_content_index="1"
data-tt_medium="twitch_directory" data-ember-action="1471">
Hey_Jase
</a>
</p>
</code></pre>
| <p>First of all, you can find all twitch channel links. Then, filter them based on the view count.</p>
<p>Something along these lines:</p>
<pre><code>import re
from selenium import webdriver
THRESHOLD = 100
driver = webdriver.Firefox()
driver.get("url")
pattern = re.compile(r"(\d+)\s+viewers on")
for link in driver.find_elements_by_css_selector("p.info a[data-tt_content=live_channel]"):
text = link.find_element_by_xpath("..").text # get to the p parent element
match = pattern.search(text) # extract viewers count
if match:
viewers_count = int(match.group(1))
if viewers_count >= THRESHOLD:
print(link.text, viewers_count)
</code></pre>
|
create index of column when same row cell of another column has today's date <p>I would like to create an index when cell in another column matches <strong>today's</strong> date. Here is my try for D2:</p>
<pre><code>=index($A2:$B14, match(today(),$A2:$A14,false ),1)
</code></pre>
<p>What am I doing wrong?
<img src="https://i.stack.imgur.com/2CpfA.png" alt="Table + formula"></p>
<p>Here is the desired Result:
<img src="https://i.stack.imgur.com/FVfX8.png" alt="Image for desired Result"></p>
| <p>If you want to retrieve the Group of items with <code>Created Time = Today()</code> then enter this formula in <code>E2:E14</code>:</p>
<pre><code>=IF(A2=TODAY(),B2,"")
</code></pre>
<p>Now if what you need is just a list of the Groups with today date enter this formula in <code>F2:F14</code>:</p>
<pre><code>=IFERROR(
INDEX($B$2:$B$14,
AGGREGATE(15,6,
(1+ROW($A$2:$A$14)-ROW($A$2))/($A$2:$A$14=TODAY()),
ROWS($A2:$A$2))),"")
</code></pre>
<p><a href="https://i.stack.imgur.com/h0dXi.png" rel="nofollow"><img src="https://i.stack.imgur.com/h0dXi.png" alt="enter image description here"></a></p>
<p><strong>EDIT TO HANDLE DATE WITH TIME</strong><br>
If the created time contains also <code>hh:mm:ss</code> then need to adjust the formula as follows:
First formula:</p>
<pre><code>=IF(INT($A2)=TODAY(),$B2,"")
</code></pre>
<p>Second formula:</p>
<pre><code>=IFERROR(
INDEX($B$2:$B$16,
AGGREGATE(15,6,
(1+ROW($A$2:$A$16)-ROW($A$2))/(INT($A$2:$A$16)=TODAY()),
ROWS($A2:$A$2))),"")
</code></pre>
<p><a href="https://i.stack.imgur.com/bNOK9.png" rel="nofollow"><img src="https://i.stack.imgur.com/bNOK9.png" alt="enter image description here"></a>
<em>Fig.2</em></p>
<p>How ever this does not account for the results shown by OP. I suggest to validate the date of the OP's machine by just entering this formula in any other cell: <code>=TODAY()</code></p>
|
SQL XML find and replace <p>So I'm dealing with a field in a table that contains XML data and from line to line the number of parameters in the XML field will vary (as will the name of the variables).</p>
<p>I need to be able to search a field containing XML for my <code><variablename>tminus1</variablename></code>
(I did not design the XML structure, I'm just the one who has to work around it) and replace the <code><ValueAsString>data here</ValueAsString></code>
with new data that is dynamically generated by a trigger that monitors table changes.</p>
<p>Because of how the XML is setup I've spent days trying to figure this out but I'm at a loss. Can anyone help? The Trigger part is easy it's find the right XML location to replace that I'm having a hard time with.</p>
<pre><code> <Parameters>
<Parameter><VariableID>(1012,14505)</VariableID><VariableName>ArtworkFormat</VariableName><ListID>(1042,1601)</ListID><ListValue>0</ListValue><ValueAsString /></Parameter>
<Parameter><VariableID>(2226,14505)</VariableID><VariableName>ArtworkProofType</VariableName><ListID>(1045,1601)</ListID><ListValue>0</ListValue><ValueAsString /></Parameter>
<Parameter><VariableID>(2224,14505)</VariableID><VariableName>ArtworkReceivedVia</VariableName><ListID>(1043,1601)</ListID><ListValue>0</ListValue><ValueAsString /></Parameter>
<Parameter><VariableID>(2225,14505)</VariableID><VariableName>ArtworkReturnVia</VariableName><ListID>(1044,1601)</ListID><ListValue>0</ListValue><ValueAsString /></Parameter>
<Parameter><VariableID>(10306,14505)</VariableID><VariableName>tminus1</VariableName><ValueAsString>10/12/2016 4:00 PM</ValueAsString></Parameter>
<Parameter><VariableID>(10308,14505)</VariableID><VariableName>tminus3</VariableName><ValueAsString>10/10/2016 4:00 PM</ValueAsString></Parameter>
<Parameter><VariableID>(10307,14505)</VariableID><VariableName>tminus2</VariableName><ValueAsString>10/11/2016 4:00 PM</ValueAsString></Parameter>
</Parameters>
</code></pre>
| <h2>One- or Two-step replacement</h2>
<p>As others pointed out, there is a problem, if you want to replace the text value of a node given as <code><ValueAsString /></code>. The <code>.modify(N'replace value of...</code> demands for a <code>/text()</code> at the end as target for the replacment, but there isn't... The simple way will work for the given case, but will not work if in the <code><Parameter></code> you want to change the target node is empty as it is in <code>VariableName="ArtworkReturnVia"</code>:</p>
<pre><code>DECLARE @SearchFor NVARCHAR(100)='tminus1';
DECLARE @SetValue NVARCHAR(100)='NewData';
UPDATE @tbl SET XmlColumn.modify(N'replace value of (/Parameters/Parameter[VariableName=sql:variable("@SearchFor")]/ValueAsString)[1]/text()[1]
with sql:variable("@SetValue")')
</code></pre>
<p>One straight approach was to delete this element in any case and do an insert:</p>
<pre><code>UPDATE @tbl SET XmlColumn.modify(N'delete (/Parameters/Parameter[VariableName=sql:variable("@SearchFor")]/ValueAsString)[1]')
UPDATE @tbl SET XmlColumn.modify(N'insert <ValueAsString>{sql:variable("@SetValue")}</ValueAsString> into (/Parameters/Parameter[VariableName=sql:variable("@SearchFor")])[1]')
</code></pre>
<h2>One more approach: <strong>Full FLWOR</strong></h2>
<pre><code>UPDATE @tbl SET XmlColumn=XmlColumn.query
('<Parameters>
{
for $p in /Parameters/Parameter
return <Parameter>
{
if($p/*/text()=sql:variable("@SearchFor")) then
for $nd in $p/*
return
if(local-name($nd)="ValueAsString") then
<ValueAsString>{sql:variable("@SetValue")}</ValueAsString>
else
$nd
else $p
}
</Parameter>
}
</Parameters>
');
</code></pre>
<h2>Another one: <strong>Semi FLWOR</strong></h2>
<pre><code>WITH Prms AS
(
SELECT ID --needs an ID here
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS NodeOrder
,p.query('.') AS prm
FROM @tbl
CROSS APPLY XmlColumn.nodes('/Parameters/Parameter') AS A(p)
)
UPDATE tbl SET XmlColumn=
(
SELECT CASE WHEN prm.value('(/Parameter/VariableName)[1]','nvarchar(max)')=@SearchFor
THEN prm.query('<Parameter>
{
for $nd in /Parameter/*
return
if(local-name($nd)="ValueAsString") then
<ValueAsString>{sql:variable("@SetValue")}</ValueAsString>
else
$nd
}
</Parameter>
')
ELSE prm END
FROM Prms
WHERE Prms.ID=tbl.ID
ORDER BY Prms.NodeOrder
FOR XML PATH(''),ROOT('Parameters')
)
FROM @tbl AS tbl
</code></pre>
|
Generating Plots from .csv file <p>I'm trying to make several plots of Exoplanet data from NASA's Exoplanet Archive. The problem is nothing I do will return the columns of the csv file with the headers on the first line of the csv file.</p>
<p>The Error I get is</p>
<pre><code> NameError: name 'pl_orbper' is not defined
</code></pre>
<p><a href="https://i.stack.imgur.com/JPKpF.png" rel="nofollow">The DATA I need to use.</a></p>
<p>The code I have currently has not worked though I'm sure I'm close.</p>
<pre><code> import matplotlib.pyplot as plt
import numpy as np
data = np.genfromtxt("planets.csv",delimiter=',',names=True, unpack=True)
plt.plot(pl_orbper,pl_bmassj)
plt.title('Mass vs Period')
plt.ylabel('Period')
plt.xlabel('Mass')
plt.show()
</code></pre>
<p>If anyone has a better solution with csv.reader or any other ways to read csv files I'd be open to it.</p>
| <p>Change the following line:</p>
<pre><code>plt.plot(pl_orbper,pl_bmassj)
</code></pre>
<p>to </p>
<pre><code>plt.plot(data['pl_orbper'],data['pl_bmassj'])
</code></pre>
<p>With the following data:</p>
<pre class="lang-none prettyprint-override"><code>rowid,pl_orbper,pl_bmassj
1, 326.03, 0.320
2, 327.03, 0.420
3, 328.03, 0.520
4, 329.03, 0.620
5, 330.03, 0.720
6, 331.03, 0.820
</code></pre>
<p>this is the result</p>
<p><a href="https://i.stack.imgur.com/ML88q.png" rel="nofollow"><img src="https://i.stack.imgur.com/ML88q.png" alt="Mass vs Period Plot"></a></p>
|
Dart Angular2 in WebStorm: "Attribute [(ngModel)] is not allowed her ..." <p>G'Day,</p>
<p>Trying to follow the Angular2 'Heros Editor' tutorial using Dart in WebStorm:</p>
<pre><code>import 'package:angular2/core.dart';
@Component( selector: 'my-app',
styleUrls: const ['app_component.css'],
template: '<input [(ngModel)]="hero" placeholder="name">')
class AppComponent{ String hero = "Seth Ladd"; }
</code></pre>
<p>The WebStorm IntelliSense marks [(ngModel)] as "Attribute [(ngModel)] is not allowed here...".</p>
<p>Am I missing an import or a setting to have WebStorm recognize Angular2 in Dart?</p>
<p>Thanks for your kind help.</p>
| <p>WebStorm doesn't support AngularDart at the moment an you may get some false warnings in injected HTML. Also you may miss Angular specific code completion, highlighting, code navigation, etc.
Watch <a href="https://youtrack.jetbrains.com/issue/WEB-11590" rel="nofollow">https://youtrack.jetbrains.com/issue/WEB-11590</a>.</p>
|
55 line C++ code crashing on debug <p>Good afternoon,</p>
<p>I am playing around with C++ and right now I'm trying to create a deck of cards. I've done what I believe has created 52 cards and then tried to call out a random one to see what number and suit it holds. When I do it builds the project and then I get a popup that says cards.exe has stopped working. I'm not sure what I've done wrong, ill post my code below also looking for suggestions on how to improve what I've already done. </p>
<p>Thanks!</p>
<pre><code> //============================================================================
// Name : cards.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
struct card {
int value; // 1-13
char suit;//H D S C
};
int main() {
char suit;
card **deck;
deck = new card *[52];
//first loop to run every card second loop to place 13 cards per suit
for (int i; i <=13; i++){
for (int j; j <=4; j++ ){
//use a s witch to determine what suit we are on
switch (j){
case 1:
suit = 'H';
break;
case 2:
suit = 'D';
break;
case 3:
suit = 'S';
break;
default:
suit = 'C';
break;
}
deck[i] = new card;
deck[i]->value = i;
deck[i]->suit= suit;
}
}
cout << deck[3]->value <<deck[3]->suit;
return 0;
}
</code></pre>
| <p>You need to initialize j in <code>for (int j; j <=4; j++ )</code>, i.e. <code>int j = 1</code>. Another issue i see is that you're overwriting <code>deck[i]</code> for all values of j.</p>
|
R: Select first and last rows of a group of emissions (one visit) and distinguish between different visits at same location <p>Working with some data on a migratory species of birds, zarapitos (genus <em>Numenius</em>), that go from Alaska, USA to MaullÃn, Chile. They stop to rest and feed on a group of islands in Chiloé. Trying to figure out how measure the amount of time they are spending on each island. The data is something like this:
Column a is time (recordings from a GPS) and column b represents where the zarapito is. This is either outside of any of the sites ("o"), in site 1 ("s1"), or site 2 ("s2"). I want to figure out how to pick out the first and last row of of each group of emissions. In the example below I would want to pull out rows 5 (the first recording we have of the zarapito at site 2) and 7 (the last recording in site 2) in order to get the difference in time (05:39 - 03:21). And then again when the zarapito is at site 1 two times (12:17 to 16:48 and 17:58 to 18:42). The actual data has the zarapito going between a number of different sites and returning to the same ones a bunch of times. </p>
<p>Was trying to use an <code>ifelse</code> statement to select only those rows that for which the following or previous row was the same for column "site" but I don't know how to remove the duplicates (Eg. Select rows 5 and 7 without 6) and also distinguish between when the zarapito visits at site 1 at 03:21, again at 12:17, and again at 17:58. In this example I don't care whether the emission at 02:34 (row 4) is included or not (would not use this emission because it's by itself). </p>
<p>Also feel free to suggest title changes to get better responses. </p>
<pre><code> ------------------
| time | site |
------------------
1| 00:12 | o |
2| 00:15 | o |
3| 00:57 | o |
4| 02:34 | s1 |
5| 03:21 | s2 |
6| 05:12 | s2 |
7| 05:39 | s2 |
8| 07:18 | o |
9| 10:44 | o |
10| 12:17 | s1 |
11| 12:49 | s1 |
12| 12:57 | s1 |
13| 15:02 | s1 |
14| 16:48 | s1 |
15| 17:13 | o |
16| 17:58 | s1 |
17| 18:20 | s1 |
18| 18:42 | s1 |
19| 19:12 | o |
20| 20:07 | o |
-------------------
df <- data.frame(time=c('00:12','00:15','00:57','02:34','03:21','05:12','05:39','07:18','10:44','12:17','12:49','12:57','15:02','16:48','17:13','17:58','18:20','18:42','19:12','20:07'),site=c('o','o','o','s1','s2','s2','s2','o','o','s1','s1','s1','s1','s1','o','s1','s1','s1','o','o') )
</code></pre>
| <p>This is probably simpler to do through <code>data.table</code>, though it would certainly be possible in base R as well. </p>
<pre><code>library(data.table)
setDT(df)
df[, rleid := rleid(site)][site!="o", if(.N > 1) .SD[c(1,.N)], by=rleid]
# rleid time site
#1: 3 03:21 s2
#2: 3 05:39 s2
#3: 5 12:17 s1
#4: 5 16:48 s1
#5: 7 17:58 s1
#6: 7 18:42 s1
</code></pre>
<p><code>rleid()</code> assigns groups based on the successive appearances at each site. Then the code just takes the first <code>1</code> and last <code>.N</code> rows from each group. Only the groups with more than one row <code>if(.N > 1)</code> are returned.</p>
|
how to tell sphinx that source code is in this path and build in that path <p>I want to run sphinx on a library in a conda virtual environment with path</p>
<pre><code>/anaconda/envs/test_env/lib/site-packages/mypackage
</code></pre>
<p>and put the html files in the path</p>
<pre><code>/myhtmlfiles/myproject
</code></pre>
<p>where my <code>conf.py</code> and <code>*.rst</code> files are in the path</p>
<pre><code>/sphinx/myproject
</code></pre>
<hr>
<p><strong><em>question</em></strong><br>
What are the <code>conf.py</code> settings I need to edit to make this happen when I run</p>
<pre><code>make html
</code></pre>
| <p><code>make</code> is not a sphinx command. That command actually runs either a <code>make</code> with a Makefile or <code>make.bat</code> (depending on your operating system), which then locates the relevant files before invoking <code>sphinx-build</code>. You will need to modify the make files and/or set the proper environmental variables.</p>
|
Show/hide visibility based on form values <p>I want to hide/show a form div based on the selection I make. I already done this, but I need a different code because I have two forms in the same code and the scripts are in conflict.</p>
<p>Please see below the code that already works, but I need a second script which will not be in conflict with the one I already have.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><script type="text/javascript">
$('#countries').on('change', function() {
if( ['1'].indexOf( this.value ) > -1 ) {
$('#state').prop('disabled', false).closest('div').show();
} else {
$('#state').val('').prop('disabled', true).closest('div').hide();
}
})
.change();
</script></code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<form>
<div class="form-row">
<label>
<span>Job title<em>*</em></span>
<select name="dropdown">
<option>Select job description</option>
<option>Select job description</option>
<option>Select job description</option>
</select>
</label>
</div>
<div class="form-row">
<label>
<span>Country<em>*</em></span>
<select name="country_list" id="countries">
<option value="">Please select</option>
<option value="1" selected="">USA</option>
<option value="2">Russia</option>
<option value="3">Canada</option>
<option value="4">Brazil</option>
<option value="4">UK</option>
</select>
</label>
<div class="form-row">
<label>
<span>State</span>
<select name="state_field" value="" id="state">
<option value="1" selected="">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
<option value="4">Arkansas</option>
<option value="5">California</option>
</select>
</label>
</div>
<div class="form-row">
<button type="submit">Register</button>
</div>
</form>
</div></code></pre>
</div>
</div>
</p>
| <p>First of all, you should not use the same id name on elements(divs, forms and selectors) for both forms.</p>
<p>Instead of, you may use class attribute to tailor your needs. Always refering jquery selector by parent form.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>
$(function () {
$('.countries').on('change', function() {
if($(this).val() == '1') {
$(this).parent().find('.states').prop('disabled', false).show();
} else {
$(this).parent().find('.states').val('').prop('disabled', true).hide();
}
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="form-1">
<h3>Form 1</h3>
<select name="country_list" id="countries-1" class="countries">
<span>Country</span>
<option value="">Please select</option>
<option value="1" selected="">USA</option>
<option value="2">Russia</option>
<option value="3">Canada</option>
</select>
<select name="state_field" value="" id="state-1" class="states">
<span>State</span>
<option value="1" selected="">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
</select>
</form>
<form id="form-2">
<h3>Form 2</h3>
<select name="country_list" id="countries-2" class="countries">
<span>Country</span>
<option value="">Please select</option>
<option value="1" selected="">USA</option>
<option value="2">Russia</option>
<option value="3">Canada</option>
</select>
<select name="state_field" value="" id="state-2" class="states">
<span>State</span>
<option value="1" selected="">Alabama</option>
<option value="2">Alaska</option>
<option value="3">Arizona</option>
</select>
</form>
</body></code></pre>
</div>
</div>
</p>
|
How to set Git config options for all subdomains? <p>Similar to how you can set <a href="http://stackoverflow.com/a/23807432/1233435">Git config options for a specific URL</a> like</p>
<p><code>git config http."https://code.example.com/".sslVerify false</code></p>
<p>I'd like to set them for all subdomains. How can I use wildcards? The following doesn't seem to work</p>
<p><code>git config http."https://*.mycompany.com/".sslCAInfo <downloaded certificate>.pem</code></p>
| <p>The analysis of the <a href="https://github.com/git/git/blob/master/urlmatch.c#L457" rel="nofollow">host matching part</a> in git's url matching procedure suggests that wildcards are not supported:</p>
<blockquote>
<pre><code>/* check the host and port */
if (url_prefix->host_len != url->host_len ||
strncmp(url->url + url->host_off,
url_prefix->url + url_prefix->host_off, url->host_len))
return 0; /* host names and/or ports do not match */
</code></pre>
</blockquote>
|
Why is my phone's IP address reported differently (depending on the site) and how can I programmatically obtain a consistent one in ASP.Net? <p>On my phone, using LTE (not wifi), if I go to whatismyipaddress.com, it reports the IP address as 166.216.xxx.xxx. But if I go to whatismyip.com, it is reported as 107.77.xxxx.xxx. Why is that?</p>
<p>When I connect to my server with my phone (again LTE, not wifi), the server-side ASP.Net code attempts to retrieve the IP address via Request.UserHostAddress, and it is always 166.216.xxx.xxx. But how can I retrieve the 107.77.xxxx.xxx address instead? I've tried using Request.ServerVariables["HTTP_CLIENT_IP"] and
Request.ServerVariables["HTTP_X_FORWARDED_FOR"] to no avail (both return null), and Request.ServerVariables["REMOTE_ADDR"] returns the same 166.216.xxx.xxx value as Request.UserHostAddress.</p>
<p>I've tried to limit the scope of my problem to the questions above, so if you can answer those sufficiently, I should (hopefully) be able to solve my issue. But in case you're wondering why this is a problem for me, read on.</p>
<p>I'm developing a phonegap application and on my production server (hosted in Azure) Request.UserHostAddress returns the 166.216.xxx.xxx IP address when I connect to it via the mobile browser (Safari) BUT returns the 107.77.xxxx.xxx IP address when I connect to it via my phonegap app. </p>
<p>I'm attempting to do so some very short-term, time-sensitive, identification of the connecting user's device when they access my server via the mobile browser (Safari), and then subsequently access it via the installed phonegap app, and the IP address figures into the algorithm, but because it's reported differently from the mobile browser vs the app it doesn't work properly.</p>
<p>At first I thought it was something to do with the how the phonegap app's network connectivity works (and it still might be) but because I'm able to get two different IP addresses reported from whatismyipaddress.com and whatismyip.com when accessing those sites via the mobile browser (Safari), I figure it has more to do with the technique used to retrieve the client IP address.</p>
<p>Any help would be greatly appreciated, Thanks.</p>
| <p>Your carrier is using CGN. That means your iPhone does not have a public IP address. The carrier whose tower you are connected to has public IP addresses, and that is what gets reported to you by a public web site.</p>
<p>The public IP address which gets reported will vary for different reasons:</p>
<ul>
<li>If you are connected to a different tower than when you checked
before, the carrier on the tower could actually be a different
carrier (different than the carrier to which you are contracted).</li>
<li>Even a single carrier can have different NAT points where your
traffic may be routed, depending on the tower to which you are connected, or how your traffic may
be routed to different other ISPs on the way to the different web
sites.</li>
</ul>
|
Npm gulp grunt difference? <p>a bit confused over those 3. Are they the same thing? I guess not since they are all in the same solution. So what do they do exactly and the relations among them? Thanks for any clarification.</p>
| <p><code>npm</code> refers to <strong>Node Package Manager</strong>. It's a package manager for node modules. You can use it form the command line to install any package registered on npm registry. People use npm to distribute packages. It host packages related to nodejs and front-end frameworks and libraries.</p>
<p><code>grunt</code> and <code>gulp</code> are pretty similar. They are both task runners that execute a list of operations and tasks that you define yourself. Both are helpful in the front-end development realm; they can be used to do a lot of things:</p>
<ul>
<li>concat, gulify JavaScript files</li>
<li>concat CSS files</li>
<li>use preprocessors to compile languages like Jade, Sass, Less, CoffeeScript</li>
<li>watch files for changes and execute tasks whenever a file change</li>
<li>optimize images</li>
<li>a lot more ...</li>
</ul>
|
How to Extract body request node.js <p>I have just started learning node.js (Express) and I created a simple application that communicate with a very simple mongo database. I have a collection called 'Users' in a database called 'testDB'. I created my skeleton in my node.js application and I followed 'separation of concern' logic.</p>
<p>In my controller folder I have a subfolder called usersController. Inside that subfolder, there is 2 .js files, one is usersControllers.js and the other is usersRoutes.js</p>
<p>Inside usersRoutes.js there is the following code:</p>
<pre><code> "use strict";
var express = require('express');
var router = express.Router();
// require the controller here
var usersController = require("./usersController.js")();
router
.get('/', usersController.getAllUsers)
.post('/', usersController.createUser);
module.exports = router;
</code></pre>
<p>As you can see, I am calling a function (factory) that is inside usersController.js called 'createUser'. This function is written like the following:</p>
<pre><code>"use strict";
var MongoClient = require('mongodb').MongoClient;
var usersController = function(){
var getAllUsers = function(req, res){
MongoClient.connect('mongodb://localhost/testDB', function(err, db){
if(err){
throw err;
}
db.collection('Users').find().toArray(function(err, doc){
if(err){
throw err;
}
else{
return res.status(200).json(doc);
db.close();
}
});
});
};
var createUser = function (req, res) {
MongoClient.connect('mongodb://localhost/testDB', function(err, db){
console.log(req.body);
db.close();
});
};
return {
getAllUsers: getAllUsers,
createUser: createUser
};
};
module.exports = usersController;
</code></pre>
<p>I have created a post man request to explore how to extract the body data that I am sending. The request is like the following </p>
<p>In the header I have 2 keys</p>
<ul>
<li>Accept: application/json;charset=UTF-8</li>
<li>Content-Type: application/json</li>
</ul>
<p>In the body I have the following raw text:</p>
<pre><code>{
"Users": {
"First Name": "Ahmed",
"Last Name": "Rahim",
"Username": "rahima1",
"Passwoed": "secure"
}
}
</code></pre>
<p>Based on the previous scenario, I have a few questions:</p>
<ol>
<li>How to extract the body from the request. I tried to dig into 'req'
but I couldn't find what I am looking for?</li>
<li>passing a plain password like that is not good, right? Any
suggestions to pass an encrypted password (maybe sha)?</li>
<li>Is there something wrong in the request itself?</li>
</ol>
<p>Any side note will help me a lot from experts like you guys :) </p>
<p>Thank you all!!</p>
| <blockquote>
<p>How to extract the body from the request. I tried to dig into 'req' but I couldn't find what I am looking for?</p>
</blockquote>
<p>This should be done with a simple <code>req.body</code>. From the <a href="http://expressjs.com/en/api.html" rel="nofollow">express docs</a> on <code>req.body</code>:
"Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer."</p>
<blockquote>
<p>passing a plain password like that is not good, right? Any suggestions to pass an encrypted password (maybe sha)?</p>
</blockquote>
<p><a href="http://stackoverflow.com/questions/2003262/how-to-send-password-securely-via-http-using-javascript-in-absence-of-https">This answer</a> sums it up pretty well. If you want to reliably encrypt password submission, you <strong>need</strong> to use https.</p>
|
Telegram Bot getUpdates VS setWebhook <p>I want to develop a bot for a business!
I don't know that using <a href="https://core.telegram.org/bots/api/#getupdates" rel="nofollow">getUpdates</a> method for develop a windows desktop application and run that on vps (by <a href="https://github.com/MrRoundRobin/telegram.bot" rel="nofollow">https://github.com/MrRoundRobin/telegram.bot</a> library)
or using <a href="https://core.telegram.org/bots/api/#setwebhook" rel="nofollow">setWebhook</a> method to develop bot with php!</p>
<p>Which one is better in terms of speed and etc?
And what are some other differences?</p>
| <p>It does not matter you want to use which kind of server side applications.
Typically <code>getUpdates</code> used for debugging. For publishing your bots, you need to using the <code>Webhook</code>. <a href="https://core.telegram.org/bots/webhooks" rel="nofollow">See this</a>.</p>
<blockquote>
<p>getUpdates is a pull mechanism, setWebhook is push.
There are some advantages of using a Webhook over getUpdates:</p>
<ol>
<li>Avoids your bot having to ask for updates frequently.</li>
<li>Avoids the need for some kind of polling mechanism in your code.</li>
</ol>
</blockquote>
|
avoid for loops in a large matrix in R <p>I have a very large matrix that requires some computation. As a for loop is notoriously slow in R, I would like to replace it with some smarter function, such as apply. However, I am scratching my head without being able to do it.</p>
<p>Here is the for loop that I wrote with a small example matrix.</p>
<pre><code>d <- matrix(c(1,1,0,0,1,1,1,0,0), 3,3)
for (i in 1:nrow(d)) {
for (j in 1:ncol(d)) {
if (d[i,j] == 1) {
d[j, i] =1
} else {d[j,i] = 0}
}
}
</code></pre>
<p>This code nicely replaces values as wish, yielding a symmetric matrix in which d[i,j] = d[j,i]. However, it can take lots of time and memory when the matrix is big. What would be an efficient alternative way to get it done? Thank you!!</p>
| <p>How about this</p>
<pre><code>d[lower.tri(d)] <- (t(d)[lower.tri(d)] == 1)
</code></pre>
<p>This gives you a symmetric matrix. Note that I'm taking the lower triangle of the transpose instead. You want to read the upper triangle row wise but <code>d[upper.tri(d)]</code> will return the column wise values. On the other hand, taking the lower triangle of the transpose is equivalent to reading the upper triangle row wise.</p>
<p>With the example you provided, taking the upper triangle work just fine because both <code>d[upper.tri(d)]</code> and <code>t(d)[lower.tri(d)]</code> will return <code>0 1 0</code>. So here is a comparison with a larger matrix:</p>
<pre><code>d <- matrix(c(1,1,0,1,0,1,0,0,0, 1,0,1,0,1,0,1), 4,4)
</code></pre>
<p>This case, <code>d[upper.tri(d)]</code> will return <code>0 0 1 0 1 0</code> whereas <code>t(d)[lower.tri(d)]</code> will return <code>0 0 0 1 1 0</code>.</p>
<p>Comparison:</p>
<pre><code>d2 <- d
d2[lower.tri(d2)] <- (t(d2)[lower.tri(d2)] == 1)
for (i in 1:nrow(d)) {
for (j in 1:ncol(d)) {
if (d[i,j] == 1) {
d[j, i] =1
} else {d[j,i] = 0}
}
}
all.equal(d2, d)
## TRUE
</code></pre>
|
Pandas Grouping - Values as Percent of Grouped Totals Not Working <p>Using a data frame and pandas, I am trying to figure out what each value is as a percentage of the grand total for the "group by" category</p>
<p>So, using the tips database, I want to see, for each sex/smoker, what the proportion of the total bill is for female smoker / all female and for female non smoker / all female (and the same thing for men)</p>
<p>For example,</p>
<p>If the complete data set is:</p>
<pre><code>Sex, Smoker, Day, Time, Size, Total Bill
Female,No,Sun,Dinner,2, 20
Female,No,Mon,Dinner,2, 40
Female,No,Wed,Dinner,1, 10
Female,Yes,Wed,Dinner,1, 15
</code></pre>
<p>The values for the first line would be (20+40+10)/(20+40+10+15), as those are the other 3 values for non smoking females</p>
<p>So the output should look like</p>
<pre><code>Female No 0.823529412
Female Yes 0.176470588
</code></pre>
<p>However, I seem to be having some trouble</p>
<p>When I do this,</p>
<pre><code>import pandas as pd
df=pd.read_csv("https://raw.githubusercontent.com/wesm/pydata- book/master/ch08/tips.csv", sep=',')
df.groupby(['sex', 'smoker'])[['total_bill']].apply(lambda x: x / x.sum()).head()
</code></pre>
<p>I get the following:</p>
<pre><code> total_bill
0 0.017378
1 0.005386
2 0.010944
3 0.012335
4 0.025151
</code></pre>
<p>It seems to be ignoring the group by and just calculating it for each line item</p>
<p>I am looking for something more like </p>
<pre><code>df.groupby(['sex', 'smoker'])[['total_bill']].sum()
</code></pre>
<p>Which will return</p>
<pre><code> total_bill
sex smoker
Female No 977.68
Yes 593.27
Male No 1919.75
Yes 1337.07
</code></pre>
<p>But I want this expressed as percentages of totals for the total of the individual sex/smoker combinations or </p>
<pre><code>Female No 977.68/(977.68+593.27)
Female Yes 593.27/(977.68+593.27)
Male No 1919.75/(1919.75+1337.07)
Male Yes 1337.07/(1919.75+1337.07)
</code></pre>
<p>Ideally, I would like to do the same with the "tip" column at the same time.</p>
<p>What am I doing wrong and how do I fix this? Thank you!</p>
| <p>You can add another grouped by process after you get the <code>sum</code> table to calculate the percentage:</p>
<pre><code>(df.groupby(['sex', 'smoker'])['total_bill'].sum()
.groupby(level = 0).transform(lambda x: x/x.sum())) # group by sex and calculate percentage
#sex smoker
#Female No 0.622350
# Yes 0.377650
#Male No 0.589455
# Yes 0.410545
#dtype: float64
</code></pre>
|
How do I invoke the OnReceive() function when a set alarm goes off? <p>I have been trying all day to invoke the BroadcastReceiver.OnReceive() function on the Android. I am using Android AIDE for my projects, but nothing seems to work. I am using...</p>
<pre><code> Intent openNewAlarm = new Intent(AlarmClock.ACTION_SET_ALARM);
startActivity(openNewAlarm);
</code></pre>
<p>to set my alarm, and a dialog comes up that allows me to set as many alarms as I would like, but instead of a ringtone, I would like to program (through an OnReceive() function) what I would like to happen instead. What can I do to achieve this? Thank you. </p>
| <p>Try this</p>
<pre><code> Intent startIntent = new Intent("BROADCAST");
PendingIntent startPIntent = PendingIntent.getBroadcast(context, 0, startIntent, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, startPIntent);
</code></pre>
<p>And then in your Manifest.xml file:</p>
<pre><code><receiver android:name="com.package.YourOnReceiver">
<intent-filter>
<action android:name="BROADCAST" />
</intent-filter>
</receiver>
</code></pre>
|
Sorting a list of Strings in Alphabetical order (C) <p>Ok, here is my problem. A teacher has to randomly select a student (from the students she has) to earn a special bonus in the final score and in order to do that she puts N pieces of paper numbered from 1 to N in a bag and randomly select a number K; the award-winning student was the K-th student in the student list. The problem is that the teacher does not know which number corresponds to which student because she lost the paper that contained this information. What she knows: the names of all students, and that, their numbers, from 1 to N, are assigned according to the alphabetical order. </p>
<p>So I need to get the set of names that is given as input, sort them alphabetically and then provide the name of the student who won the special bonus, but I'm having trouble doing so. The program I wrote orders all the names except the first. </p>
<p>In addition, the following warnings appear when I run the project with Code::Blocks: </p>
<ul>
<li>(line 16) ISO C90 forbids array variable length 's' [-Wvla] </li>
<li>(Line 13) ISO C90 forbids mixed declarations and code [-Wpedantic]</li>
</ul>
<p>Please, tell me what am I doing wrong here and if there's a better way to sort the names without having the specified amount of names. </p>
<p>Note: the program should stop reading the input when N and K are equal to zero.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n, k, i, j=0, aux, numMenorNome;
char str[]="zzzzzzzzzzzzzzzzzzzz", str2[]="zwyxzzzzzzzzzzzzzzzz";
do
{
scanf("%d%d", &n, &k);
struct student
{
char nome[21]; /*name*/
char nomes_ordenados[21]; /*array to put the names already sorted*/
} s[n];
for (i=0; i<n; i++)
{
scanf(" %s", s[i].nome);
}
for (i=0; i<n; i++)
{
aux = strcmp(str, s[i].nome); /*compares the string that would be the last in the alphabetical order ("zzzzzzzzzzzzzzzzzzzz") with the given names*/
if(aux>0)
{
strcpy(str, s[i].nome); /*it gives me the name that comes first in alphabetical order */
numMenorNome = i; /* identification number of the name that was obtained */
}
if (i==(n-1))
{
strcpy(s[j].nomes_ordenados,str);
printf("%s\n", s[j].nomes_ordenados);
strcpy(str, "zzzzzzzzzzzzzzzzzzzz");
strcpy(s[numMenorNome].nome, str2);
j++;
i=0; /* restarts the loop in order to obtain the second name in alphabetical order, the third name, the fourth name and so on */
if(j==n)
break;
}
}
printf("%s\n\n", s[k-1].nomes_ordenados);
} while (n!=0&&k!=0);
return 0;
}
</code></pre>
| <p>Sorting an array of strings are real simple. Just use <code>qsort</code> and the existing compare function (i.e. <code>strcmp</code>)</p>
<p>Example:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMES 5
#define NAME_LEN 10
void print_names(char names[][10])
{
int i;
for(i=0; i<NAMES; ++i)
{
printf("%s\n", names[i]);
}
}
int main(void) {
char names[NAMES][NAME_LEN] = { "xxx", "uuu", "ccc", "aaa", "bbb" };
print_names(names);
printf("---------------------------------\n");
qsort(names, NAMES, NAME_LEN, strcmp);
print_names(names);
return 0;
}
</code></pre>
|
Ember SyntaxError Unexpected Token; NodeJS Module Related <p>I am having an issue with Ember building. I have tried doing <code>npm clean cache</code>, deleting the <code>node_modules</code> folder, and then <code>npm install</code>. I have also tried copying the <code>ember-cli</code> and <code>ember-cli-htmlbars-inline-precompile</code> folders from sources that I know build correctly and are using the same versions.</p>
<pre><code>SyntaxError: Unexpected token :
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Project.require (*****\node_modules\ember-cli\lib\models\project.js:280:12)
at Project.config (*****\node_modules\ember-cli\lib\models\project.js:198:26)
at Class.module.exports.projectConfig (*****\node_modules\ember-cli-htmlbars-inline-precompile\index.js:103:25)
</code></pre>
| <p>After searching and searching, I ran across <a href="http://discuss.emberjs.com/t/server-wont-start-syntaxerror-unexpected-identifier-at-exports-runinthiscontext-vm-js-53-16/9012" rel="nofollow">this question</a>. It turns out that my /config/environment.js was corrupt, which was resulting in this error.</p>
|
Labeling y-axis with multiple x-axis' <p>I've set up a plot with 3 x-axis' on different scales, however when i attempt to use a Y-label i get the error: </p>
<p>AttributeError: 'function' object has no attribute 'ylabel'</p>
<p>I've tried a number of options, however I am not sure why this error appears.</p>
<p>My code:</p>
<pre><code>fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.30)
ax1 = ax.twiny()
ax2 = ax.twiny()
ax1.set_frame_on(True)
ax1.patch.set_visible(False)
ax1.xaxis.set_ticks_position('bottom')
ax1.xaxis.set_label_position('bottom')
ax1.spines['bottom'].set_position(('outward', 60))
ax.plot(temp1, depth1, "r-")
ax1.plot(v1, depth1, "g-.")
ax2.plot(qc1, depth1, "b--")
ax1.axis((0, 200, 0, 20))
ax.invert_yaxis()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.set_xlabel('Temperature [\N{DEGREE SIGN}C]', color='r')
ax1.set_xlabel('Volumetric moisture content [%]', color='g')
ax2.set_xlabel('Cone tip resistance [MPa]', color='b')
ax.set.ylabel('Depth [m]')
for tl in ax.get_xticklabels():
tl.set_color('r')
for tl in ax1.get_xticklabels():
tl.set_color('g')
for tl in ax2.get_xticklabels():
tl.set_color('b')
ax.tick_params(axis='x', colors='r')
ax1.tick_params(axis='x', colors='g')
ax2.tick_params(axis='x', colors='b'
</code></pre>
<p>)</p>
| <p>you are typing ax.set.ylabel, you should be doing ax.set_ylabel</p>
|
Android manipulating Listview items outside screen throws nullpointer exception <p>I'm making an mp3 player app. </p>
<p>In order to better highlight which song is playing, I change the background color of the current song's listitem.</p>
<p>Everything works fine when I click on the actual list items using the onItemClickListener. I can also auto update to highlight the next song after the current one has finished.</p>
<p>However only when the next song list item is on screen. Same goes if I am on the first song and press back to go to the last song in the list. The song plays fine, but i get a null pointer exception on the list item when I try to set the background color.</p>
<p>Update color method: (I get the nullpointer on the last line #ff9966</p>
<pre><code>public static void updateSongColor() {
if (currentSongPos == songs.size()-1) {
currentSongPos = 0;
}
else {
currentSongPos++;
}
currentSongView.setBackgroundColor(Color.parseColor("#FFFFFF"));
currentSongView = listView.getChildAt(currentSongPos);
currentSongView.setBackgroundColor(Color.parseColor("#ff9966"));
}
</code></pre>
<p>Maybe because it isn't inflated yet? I actually don't know.</p>
<p>How do I inflate or "load" the view I want to change color of dynamically?</p>
<p>I have tried:</p>
<pre><code>.setSelection()
</code></pre>
<p>Before changing the background color, but that made no difference, I thought since I move to it, it will be "loaded" and thus not null.</p>
<p>This question is different from other similar ones because I want to know how I can "Pre-load" a view that is outside the screen and alter it's parameters (background color).</p>
<p>Here is my adapter class if it matters, and feel free to request more code snippets because I don't know what might be relevant here.</p>
<pre><code>public class PlayListAdapter extends ArrayAdapter<Song> {
public PlayListAdapter(Context context, ArrayList<Song> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View row, ViewGroup parent) {
Song data = getItem(position);
row = getLayoutInflater().inflate(R.layout.layout_row, parent, false);
TextView name = (TextView) row.findViewById(R.id.label);
name.setText(String.valueOf(data));
row.setTag(data);
return row;
}
}
</code></pre>
<p>Thanks!</p>
| <p>If I do, I update view in PlayListAdpater.<br>
I'm adding variable for selected position in adapter.<br>
And I'm changing it when next song play.</p>
<p>If you call 'updateSongColor' in Service, you can use broadcast or AIDL. </p>
<p>Example)</p>
<pre><code>public class PlayListAdapter extends ArrayAdapter<Song> {
private int currentSongPos =-1; // init
...
public void setCurrentSong(int pos) {
currentSongPos = pos;
}
...
@Override
public View getView(int position, View row, ViewGroup parent) {
....
if(currentSongPos == position)
currentSongView.setBackgroundColor(Color.parseColor("#ff9966"));
else
currentSongView.setBackgroundColor(Color.parseColor("#FFFFFF"));
....
}
}
....
....
// call updateSongColor
public void updateSongColor() {
if (currentSongPos == songs.size()-1) {
currentSongPos = 0;
}
else {
currentSongPos++;
}
PlayListAdapter.setCurrentSong(currentSongPos);
PlayListAdapter.notifyDataSetChanged();
}
...
</code></pre>
|
Reading from and writing to registers of an IMU via UART <p>I have an IMU that has a UART interface. The manufacturer has provided a Windows based program that get all the data from the IMU and displays it in real time. (The device is connected to the PC via the USB). I need to write my own software that does this in order to integrate it into my project. </p>
<p>The datasheet/manual for the IMU gives all details about which registers have to be written to and read from (issue commands and read responses) in order to get the IMU data. My question is, how do I implement this in C under Linux? </p>
<p>The closest information I found out was <a href="https://sysplay.in/blog/linux-device-drivers/2013/09/accessing-x86-specific-io-mapped-hardware-in-linux/" rel="nofollow">this one</a> but when compiling it it seems I need Linux kernel headers since that program uses <code>#include <linux/module.h></code> so I'm not sure if I am on the right track.</p>
| <p>You need not any kernel headers to talk over a serial port with any device connected to that serial port. </p>
<p>You would get a 'connection' to your device by simply opening a file <code>/dev/ttyUSB0</code> with <code>open()</code> call (the actual name could be found by looking into <code>dmesg</code> for relevant device messages or by looking what device node appears under <code>/dev</code> when you plug your device into <code>usb</code> port).
Then you would need to set the baud rate and the word format (number of bits, parity and number of stop bits). To achieve that from the user-space process you would use a set of <code>ioctl</code>s. For details read <code>man ioctl</code> and <code>man ioctl_list</code></p>
|
Iterate through list, adding to array <p>I have a <code>List<PaymentObject></code></p>
<p>A Payment Object consists of:</p>
<blockquote>
<p>DateTime PaymentDate; Decimal Amount;</p>
</blockquote>
<p>What I need to do is create an array that ends up like this:</p>
<pre><code> s.Data = new Data(new object[,]
{
{ new DateTime(1970, 9, 27), 0 },
{ new DateTime(1970, 10, 10), 0.6 },
{ new DateTime(1970, 10, 18), 0.7 },
{ new DateTime(1970, 11, 2), 0.8 },
{ new DateTime(1970, 11, 9), 0.6 },
{ new DateTime(1970, 11, 16), 0.6 },
{ new DateTime(1970, 11, 28), 0.67 },
{ new DateTime(1971, 1, 1), 0.81 },
{ new DateTime(1971, 1, 8), 0.78 },
{ new DateTime(1971, 1, 12), 0.98 },
{ new DateTime(1971, 1, 27), 1.84 },
{ new DateTime(1971, 2, 10), 1.80 },
{ new DateTime(1971, 2, 18), 1.80 },
{ new DateTime(1971, 2, 24), 1.92 },
{ new DateTime(1971, 3, 4), 2.49 },
{ new DateTime(1971, 3, 11), 2.79 },
{ new DateTime(1971, 3, 15), 2.73 },
{ new DateTime(1971, 3, 25), 2.61 },
{ new DateTime(1971, 4, 2), 2.76 },
{ new DateTime(1971, 4, 6), 2.82 },
{ new DateTime(1971, 4, 13), 2.8 },
{ new DateTime(1971, 5, 3), 2.1 },
{ new DateTime(1971, 5, 26), 1.1 },
{ new DateTime(1971, 6, 9), 0.25 },
{ new DateTime(1971, 6, 12), 0 }
});
</code></pre>
<p>How can I foreach through my list, and add each item to the Array?</p>
| <p>One way might look like:</p>
<pre><code>var paymentObjectList = new List<PaymentObject>();
// assuming the above gets populated at some point
object[,] dataArray = new object[paymentObjectList.Count, 2];
int listIndex = 0;
foreach (var paymentObject in paymentObjectList)
{
dataArray[listIndex, 0] = paymentObject.PaymentDate;
dataArray[listIndex, 1] = paymentObject.Amount;
listIndex++;
}
// resuming your original code
s.Data = new Data(dataArray);
</code></pre>
|
Import os doesn't not work in linux <p>I just want to install the <a href="https://pypi.python.org/pypi/suds" rel="nofollow">suds library</a>, but suddenly it wasn't proceeding because it was not finding the <code>os</code> library, so I tried to open my python and it results me an error. When I import the <code>os</code> library and there are some errors during the opening as well. Please, see the snapshot of my error when importing the library mentioned.</p>
<p><a href="https://i.stack.imgur.com/Q4S7e.png" rel="nofollow"><img src="https://i.stack.imgur.com/Q4S7e.png" alt="enter image description here"></a></p>
<p>Is there any solution for this? Or do I need to reinstall python?</p>
| <p>You need to <a href="https://www.python.org/downloads/" rel="nofollow">install a more recent version of Python - version 2.7.12 or later</a>. <a href="http://www.snarky.ca/stop-using-python-2-6" rel="nofollow">All versions of Python 2.6 have been end-of-lifed and any use of Python 2.6 is actively discouraged</a>.</p>
|
Making a PHP Button Clickable <p>Firstly, thanks so much for your help.</p>
<p>I am creating a Wordpress site for a client which you can see here: <a href="http://christchurchhelicopters.co.nz/new" rel="nofollow">http://christchurchhelicopters.co.nz/new</a></p>
<p>Essentially, for user experience, we want to make each of the tours clickable (as in the image as well). This is because at the moment, all that's clickable is the title, which isn't obvious.</p>
<p>I found the code where it's all stored, but can't work out a way to put the link to the tour URL into the href tags.</p>
<p>Code:</p>
<pre><code><?php
/**
* @package WordPress
* @subpackage Travel Time
* @version 1.0.0
*
* Posts Slider Standard Tour Format Template
* Created by CMSMasters
*
*/
$cmsmasters_metadata = explode(',', $cmsmasters_project_metadata);
$title = (in_array('title', $cmsmasters_metadata)) ? true : false;
$excerpt = (in_array('excerpt', $cmsmasters_metadata) && travel_time_project_check_exc_cont()) ? true : false;
$categories = (get_the_terms(get_the_ID(), 'pj-categs') && (in_array('categories', $cmsmasters_metadata))) ? true : false;
$comments = (comments_open() && (in_array('comments', $cmsmasters_metadata))) ? true : false;
$likes = (in_array('likes', $cmsmasters_metadata)) ? true : false;
$icon = in_array('icon', $cmsmasters_metadata) ? true : false;
$duration = in_array('duration', $cmsmasters_metadata) ? true : false;
$participants = in_array('participants', $cmsmasters_metadata) ? true : false;
$price = in_array('price', $cmsmasters_metadata) ? true : false;
$rating = in_array('rating', $cmsmasters_metadata) ? true : false;
$cmsmasters_project_icon = get_post_meta(get_the_ID(), 'cmsmasters_project_icon', true);
$cmsmasters_project_duration = get_post_meta(get_the_ID(), 'cmsmasters_project_duration', true);
$cmsmasters_project_participants = get_post_meta(get_the_ID(), 'cmsmasters_project_participants', true);
$cmsmasters_project_price = get_post_meta(get_the_ID(), 'cmsmasters_project_price', true);
$cmsmasters_project_link_url = get_post_meta(get_the_ID(), 'cmsmasters_project_link_url', true);
$cmsmasters_project_link_redirect = get_post_meta(get_the_ID(), 'cmsmasters_project_link_redirect', true);
?>
<!--_________________________ Start Standard Tour _________________________ -->
<article id="post-<?php the_ID(); ?>" <?php post_class('cmsmasters_slider_project'); ?>>
<div class="cmsmasters_slider_project_outer">
<div class="project_outer_image_wrap">
<?php
if ($icon || $price || $categories || $title || $likes || $comments) {
echo '<div class="project_outer_image_wrap_meta entry-meta">';
$icon ? travel_time_project_icon($cmsmasters_project_icon) : '';
$price ? travel_time_project_price($cmsmasters_project_price, 'page') : '';
if ($categories || $title || $likes || $comments) {
echo '<div class="project_outer_image_wrap_meta_bottom entry-meta">';
$categories ? travel_time_get_slider_post_category(get_the_ID(), 'pj-categs', 'project') : '';
$title ? travel_time_slider_post_heading(get_the_ID(), 'project', 'h2', $cmsmasters_project_link_redirect, $cmsmasters_project_link_url) : '';
$comments ? travel_time_get_slider_post_comments('project') : '';
$likes ? travel_time_slider_post_like('project') : '';
echo '</div>';
}
echo '</div>';
}
travel_time_thumb_rollover(get_the_ID(), 'cmsmasters-tour-thumb', false, true, false, false, false, false, false, false, true, $cmsmasters_project_link_redirect, $cmsmasters_project_link_url);
echo '</div>';
if ($excerpt || $duration || $participants || $rating ) {
echo '<div class="project_inner">';
$excerpt ? travel_time_slider_post_exc_cont('project') : '';
echo '<footer class="cmsmasters_project_footer entry-meta">';
$duration ? travel_time_project_duration($cmsmasters_project_duration, 'page') : '';
$participants ? travel_time_project_participants($cmsmasters_project_participants, 'page') : '';
if (CMSMASTERS_SIMPLE_RATING && $rating ) {
travel_time_simple_rating(get_the_ID(), 'page');
}
echo '</footer>';
echo '</div>';
}
?>
</div>
</article>
<!--_________________________ Finish Standard Tour _________________________ -->
</code></pre>
| <p>I'm reading from mobile, so hope I'm not missing something on the code above, but seems that the function <strong>travel_time_thumb_rollover</strong> is responsible of printing the link. Try looking for it with a recursive full text search in your project folder.
Basically you should unwrap the <code><a></code> around the title to put it around the whole thumbnail. </p>
|
Yii2 Custom / Shorter Namespace <p>I have a nested 'mail' module in my yii2 (basic template) at this location:</p>
<blockquote>
<p>@app/modules/admin/modules/mail</p>
</blockquote>
<p>How do I create shorter namespaces in all of the modules files. So instead of this namespace in my controller files:</p>
<blockquote>
<p>namespace app\modules\admin\modules\mail\controllers;</p>
</blockquote>
<p>I could just have:</p>
<blockquote>
<p>namespace mail/controllers;</p>
</blockquote>
<p>If I ever move the module folder, I wouldn't have to go and manually change the namespace in every single file (also they're just long).</p>
<p>The docs actually recommend this here <a href="http://www.yiiframework.com/doc-2.0/guide-structure-modules.html#nested-modules" rel="nofollow">http://www.yiiframework.com/doc-2.0/guide-structure-modules.html#nested-modules</a> where it says "<strong>you should consider using a shorter namespace here!</strong>"</p>
<p>But how do you accomplish this?</p>
| <p>you must set alias to directory at bootstrap to custom namespace.</p>
<p>First, create a <code>bootstrap.php</code> in <code>config/</code> folder:</p>
<pre><code>//bootstrap.php
Yii::setAlias('mail', dirname(dirname(__DIR__)) . '/modules/admin/modules/mail');
</code></pre>
<p>Add run <code>bootstrap.php</code> at init app.</p>
<p>Edit file <code>web/index.php</code>, add this line after require <code>Yii.php</code></p>
<pre><code>require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
//Add after require Yii.php
require(__DIR__ . '/../config/bootstrap.php');
$config = require(__DIR__ . '/../config/web.php');
(new yii\web\Application($config))->run();
</code></pre>
<p>Now you can set namespace for controllers in mail module is <code>mail/controllers</code>.</p>
<p>Hope it helpful.</p>
|
All Unique Permutations - Stack overflow issue <p>I am trying to solve the following problem:</p>
<blockquote>
<p>Given a collection of numbers that might contain duplicates, return
all possible unique permutations.</p>
</blockquote>
<p>Here is my code:</p>
<pre><code>public class Solution {
public ArrayList<ArrayList<Integer>> permute(ArrayList<Integer> a) {
HashMap<ArrayList<Integer>, Boolean> unique = new HashMap<>();
ArrayList<ArrayList<Integer>> results = new ArrayList<>();
permu(results, a, 0, unique);
return results;
}
private void permu(ArrayList<ArrayList<Integer>> results, final ArrayList<Integer> a, int item, HashMap<ArrayList<Integer>, Boolean> unique) {
for(int i = 0; i < a.size(); i++) {
ArrayList<Integer> aClone = new ArrayList<>(a);
// swap
int backup = aClone.get(i);
aClone.set(i, aClone.get(item));
aClone.set(item, backup);
if(!unique.containsKey(aClone)) {
results.add(aClone);
unique.put(aClone, true);
permu(results, aClone, i, unique); //<--- Stack overflow error
}
}
}
}
</code></pre>
<p>I have a stack overflow error on this the call to the recurrence, line (19)</p>
| <p>Well, I don't like to ruin good job interview questions, but this question was fun to think about, so...</p>
<p>Here's a super-L337 answer for generating all unique permutations very quickly and without using much memory or stack. If you use this in a job interview, the interviewer will ask you to explain how it works. If you can do that, then you deserve it :)</p>
<p>Note that I permuted the chars in a string instead of the instead of integers in a list, just because it's easier to pretty-print the result.</p>
<pre><code>import java.util.Arrays;
import java.util.function.Consumer;
public class UniquePermutations
{
static void generateUniquePermutations(String s, Consumer<String> consumer)
{
char[] array = s.toCharArray();
Arrays.sort(array);
for (;;)
{
consumer.accept(String.valueOf(array));
int changePos=array.length-2;
while (changePos>=0 && array[changePos]>=array[changePos+1])
--changePos;
if (changePos<0)
break; //all done
int swapPos=changePos+1;
while(swapPos+1 < array.length && array[swapPos+1]>array[changePos])
++swapPos;
char t = array[changePos];
array[changePos] = array[swapPos];
array[swapPos] = t;
for (int i=changePos+1, j = array.length-1; i < j; ++i,--j)
{
t = array[i];
array[i] = array[j];
array[j] = t;
}
}
}
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder line = new StringBuilder();
generateUniquePermutations("banana", s->{
if (line.length() > 0)
{
if (line.length() + s.length() >= 75)
{
System.out.println(line.toString());
line.setLength(0);
}
else
line.append(" ");
}
line.append(s);
});
System.out.println(line);
}
}
</code></pre>
<p>Here is the output:</p>
<pre><code>aaabnn aaanbn aaannb aabann aabnan aabnna aanabn aananb aanban aanbna
aannab aannba abaann abanan abanna abnaan abnana abnnaa anaabn anaanb
anaban anabna ananab ananba anbaan anbana anbnaa annaab annaba annbaa
baaann baanan baanna banaan banana bannaa bnaaan bnaana bnanaa bnnaaa
naaabn naaanb naaban naabna naanab naanba nabaan nabana nabnaa nanaab
nanaba nanbaa nbaaan nbaana nbanaa nbnaaa nnaaab nnaaba nnabaa nnbaaa
</code></pre>
|
Random increase in div height for dynamic content <p>I'm adding html tags dynamically into a div, unless the div's height has reached 700px, after which I'm adding new tags to a separate div, like this:</p>
<pre><code>while (index < contents.length) {
var content = contents.eq(index).clone();
var previousHeight = heightTesterDiv.height();
heightTesterDiv.append(content);
var newHeight = heightTesterDiv.height();
console.log('Div content: '+content[0].outerHTML +' .Div Height Increased: '+(newHeight - previousHeight));
if (heightTesterDiv.height() > 700) {
// other code
}
}
</code></pre>
<p>However, the increase in height after adding tags seems random: <a href="https://i.stack.imgur.com/1lnRE.png" rel="nofollow"><img src="https://i.stack.imgur.com/1lnRE.png" alt="enter image description here"></a></p>
<p>We can see that <code><br></code> is sometimes increasing the height by 0px, while sometimes by 30px.
Is this an expected behaviour ?</p>
<p>EDIT: Live fiddle: <a href="http://jsbin.com/semepejahu/2/edit?html,css,js,console,output" rel="nofollow">http://jsbin.com/semepejahu/2/edit?html,css,js,console,output</a></p>
| <p>I'm thinking this is the css display values at play here.</p>
<p>Some elements come with a few built in styles..for example some browsers give h1 and h4 tags "display: block;" styling by default.</p>
<p>The gist of the difference is that inline elements can be side by side and block is designed so the elements get their own "line". But for some reason these two values completely change how the styling margins work. </p>
<p>You can inspect/query the 'br' tags and always find they never have height,in either case...so you know they don't directly cause this issue.</p>
<p>If you add some css to your fiddle:</p>
<pre><code>h1, h4 {
display: inline-block;
}
</code></pre>
<p>you'll notice the 'br' tags don't contribute more height. Elements with</p>
<pre><code>display: block;
</code></pre>
<p>will cause the parent div to increase in size when pushed up against other elements due to this interpretation of margins. Even elements with no realistic size like our 'br' tags.</p>
<p>But yeah...why those amounts... ¯\_(ã)_/¯</p>
|
Error in expected output: Loop is not correctly working <p>I am still struggling to link the second 'for' variable in this together. The first 'for' loop works correctly, but the second half is stuck on a single variable, which is not allowing it to function correctly in a later repeatable loop. How might I write this better, so that the functions of the text are global, so that the variable 'xcr' isnt local. I know I am a beginner, but any help is always appreciated!! Thanks!</p>
<pre><code>sequence = open('sequence.txt').read().replace('\n','')
enzymes = {}
fh = open('enzymes.txt')
print('Restriction Enzyme Counter')
def servx():
inez = input('Enter a Restricting Enzyme: ')
for line in fh.readlines():
(name, site, junk, junk) = line.split()
enzymes[name] = site
global xcr
xcr = site
if inez in line:
print(xcr)
print('Active Bases:', xcr)
for lines in sequence.split():
if xcr in lines:
bs = (sequence.count(xcr))
print(bs)
print('Enzyme', inez, 'appears', bs, 'times in Sequence.')
</code></pre>
| <p>I think you need to specify global inside the <code>servy</code> function and not outside, but even better would be to pass inez as a parameter to <code>servx</code>:</p>
<pre><code>def servy():
global inez
fh.seek(0); #veryyyyy important
qust = input('Find another Enzyme? [Yes/No]: ')
qust = qust.lower()
if qust == 'yes':
inez = input('Enter a Restricting Enzyme: ')
servx()
servy()
elif qust == 'no':
print('Thanks!')
elif qust not in ('yes', 'no'):
print('Error, Unknown Command')
</code></pre>
<hr>
<p>Or</p>
<pre><code>def servx(inez):
. . .
def servy():
fh.seek(0); #veryyyyy important
qust = input('Find another Enzyme? [Yes/No]: ')
quest = qust.lower()
if qust == 'yes':
inez = input('Enter a Restricting Enzyme: ')
servx(inez)
servy()
elif qust == 'no':
print('Thanks!')
elif qust not in ('yes', 'no'):
print('Error, Unknown Command')
</code></pre>
|
How should i fix with ng-invalid and ng-pristine in angular validation? <p>i have a issue about angular validation.</p>
<p>My case point:</p>
<ol>
<li>I have 2 textfields and 1 button in a form.</li>
<li>When page load, the button is by ng-disabled with ng-invalid status.</li>
<li>Then type something text in a textfield, the button ng-disabled to unlock.</li>
<li>[Problem] When i clear all text in a textfield such as delete key with keyboard, the button ng-disabled not to unlock status.</li>
<li>If not use ãrequiredãwith textfield.</li>
</ol>
<p>I already put in <a href="https://jsfiddle.net/uyx1swu3/3/" rel="nofollow">jsfiddle</a></p>
<pre><code><div ng-controller="validationCtrl">
<form name="xyzForm" novalidate>
<input
type="text"
name="name"
ng-model="xname"
ng-class="{'has-error': xyzForm.name.$invalid && !xyzForm.name.$pristine}"
/>
<input
type="number"
name="age"
ng-model="xage"
ng-class="{'has-error': xyzForm.age.$invalid && !xyzForm.age.$pristine && xyzForm.age.$dirty}"
/>
<div>
<button ng-click="submit()" ng-disabled="xyzForm.$invalid || xyzForm.$pristine">Submit</button>
<span>invalid : {{xyzForm.$invalid}}</span>
<span>pristine : {{xyzForm.$pristine}}</span>
</div>
</form>
</div>
</code></pre>
| <p>I consider you don't want to user "Required" Attribute for both textfield and as below you can use </p>
<pre><code><div ng-app="appX">
<div ng-controller="validationCtrl">
<form name="xyzForm" novalidate>
<input
type="text"
name="name"
ng-model="xname"
ng-class="{'has-error': xyzForm.name.$invalid && !xyzForm.name.$pristine}"
/>
<input
type="number"
name="age"
ng-model="xage"
ng-class="{'has-error': xyzForm.age.$invalid && !xyzForm.age.$pristine && xyzForm.age.$dirty}"
/>
<div>
<button ng-click="submit()" ng-disabled="(xyzForm.$invalid || xyzForm.$pristine) || !xage || xname
==''">Submit</button>
<span>invalid : {{xyzForm.$invalid}}</span>
<span>pristine : {{xyzForm.$pristine}}</span>
</div>
</form>
</div>
</div>
</code></pre>
|
responsive div blocks don't align properly on mobile device <p>I have a shift calendar for a local fire department that I built using foundation5 responsive css framework. Everything works great when viewing in my browser and resizing the window.<br>
<strong>example:</strong></p>
<p><a href="https://i.stack.imgur.com/c3ZvG.png" rel="nofollow"><img src="https://i.stack.imgur.com/c3ZvG.png" alt="enter image description here"></a></p>
<p>However, when I view this on an iPhone the calendar days are moved one block up.</p>
<p><a href="https://i.stack.imgur.com/5EJdA.png" rel="nofollow"><img src="https://i.stack.imgur.com/5EJdA.png" alt="enter image description here"></a></p>
<p>Here is my css:</p>
<pre><code>.calRow {
max-width:100%;
}
.calMonth, .calPrev, .calNext {
text-transform:uppercase;
font-weight:bold;
color:gray;
font-size:1.7em;
margin:15px 0;
text-align:center;
}
.calMonth {
text-align:center;
}
.calPrev {
text-align:left;
}
.calNext {
text-align:right;
}
.pCal ul li {
text-align:center;
height:0;
padding:0 0 14.28571%;
border-left:solid 1px gray;
border-top:solid 1px gray;
position: relative;
}
.pCal ul li:after {
content:'';
display: block;
margin-top: 100%;
}
.pCal ul li dl {
position:relative;
padding:0;
margin:0;
top:0;
height:100%;
}
.pCal ul li dl dt {
padding:0;
margin:0;
}
.pCal ul li.calHead {
font-size:0.8em;
border:none;
color:gray;
height:25px;
margin-bottom:-20px;
}
.calToday {
border-bottom:0.5em solid lightGrey;
}
.calDay {
position:relative;
padding:15%;
margin:0;
top:-100%;
}
.calLayer2, .calLayer3, .calLayer4 {
position:relative;
padding:0;
}
.calLayer2 {
top:-200%;
}
.calLayer3 {
top:-300%;
}
.calLayer4 {
top:-400%;
}
/* SHIFT HEIGHT / SIZE STYLES */
.shift2 {
height:50%
}
.shift3 {
height:33.33%
}
.shift4 {
height:25%
}
/* OVERLAY STYLES */
.calX img{
width:100%;
padding-top:2%;
}
.calCircle img{
width:100%;
padding:9% 7%;
}
.calSquare img {
width:100%;
padding:7%;
}
.pCal .calDayParts {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
.pCal .calDayOverlay {
position: absolute;
top: 0;
bottom: 0;
height: auto;
width:100%;
}
.calLayer1, .calLayer2, .calLayer3 {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</code></pre>
<p>Can someone help me figure out why this is or at least suggest a way to debug it.</p>
<p>Thanks</p>
<h2>EDIT 1 JS FIDDLE LINK</h2>
<p><a href="https://jsfiddle.net/krisis/vtwj4v2o/" rel="nofollow">GO HERE</a> for jsfiddle example - same issue is present when viewed on phone</p>
<p>side note, <a href="http://stackoverflow.com/a/3132119/1854382">this answer</a> has instructions on how to use iPhone over local network to connect to localhost of IIS on windows PC</p>
| <p>It's difficult to debug without being able to inspect the site first hand. From first glance though, I would try adding a float and clear to the .calRow class, provided it is what it sounds like (the rows that make up the calendar).</p>
<pre><code>.calRow {
float: left;
clear: both;
width: 100%;
}
</code></pre>
<p>Keep in mind by floating the calendar rows you will most likely need to also float the calendar container.</p>
<p>If that doesn't solve the problem it's most likely related to your absolute positioned elements not being positioned relatively to their parent element.</p>
<p>EDIT: I should add, if you have access to safari, an iPhone and a cord to plug the iPhone into your desktop. You can inspect the site using safari on your desktop by going to 'Develop' > 'iPhone'. <a href="http://appletoolbox.com/2014/05/use-web-inspector-debug-mobile-safari/" rel="nofollow">More info on remote debugging here.</a></p>
|
How to access page by address in APEX <p>In the interactive report I developed with Apex, the table on the home page shows the information of a list of projects, including project name, owner etc. And the project name field of each project is a click which redirect to another page that shows more detailed project's information. In short, there is a link on the home page which directs to the page A. Sometimes, I need to copy and paste the address of this page A and send it to my colleagues so that they can go to that page directly by copying the address to their browser. However, when Iãtried to use the address to view the page, I got redirect to the home page instead of page A. Why this is the case? How can I achieve the redirection I want in APEX?</p>
<p>P.S. My APEX application do have access control where only authorised people can create and edit items in the report, but everyone can view the item and the page A is the viewing page. I am not sure if this access control have anything to do with the issue.</p>
| <p>I got the answer from APEX forum, so I am gonna write the answer here so that it might be of some help. </p>
<p>The url has a session id, which belongs to the app. By default, if you copy and paste this address to another browser, a new session will be created and the old id will not be valid anymore and the url will redirect you to the login page or the home page. If you want to make this url valid all the time, you need change the deep link attribute to be enabled under the authentication. Please refer to <a href="https://docs.oracle.com/database/121/HTMDB/bldr_attr.htm#CHDHIFEJ" rel="nofollow">Deep Linking</a> for more details.</p>
|
verilog fwrite output bytes <p>I know that if I am outputting a binary file in verilog, then I can use the following verilog IO standard function:</p>
<pre><code>$fwrite(fd,"%u",32'hABCDE124);
</code></pre>
<p>But the above command writes 4-byte data into the file. What if the binary data that I want to write is only one-byte, two-bytes or three-bytes?
How can I do this?</p>
<p>For example, I know the following won't do what I want:</p>
<pre><code>$fwrite(fd,"%u",8'h24);
$fwrite(fd,"%u",16'hE124);
$fwrite(fd,"%u",24'hCDE124);
</code></pre>
<p>Is there any way that I can write a non 4-byte multiple data into a file?</p>
<p>Thanks, </p>
<p>--Rudy </p>
| <p>You can use <code>%c</code> to write out a single byte. You can use a bit-stream cast to convert your data into an array of bytes, then do</p>
<pre><code>foreach(array_of_bytes[i]) $fwrite(fd,"%c",array_of_bytes[i]);
</code></pre>
<p>If you have a large amount of data, you may want to optimize this by writing out the multiple of 4-bytes with <code>%u</code>, and the remaining bytes with `%c'.</p>
|
Setting the JS dropdown selection checkmark in an appropriate position and make dropdown list look better <p>I am trying to implement a dropdown/selection list in JS and here is what I have written:</p>
<pre><code>//some js code
#startJobDialog (A dialog box in JS)
// js code
var markUp = "<ul id='topMenu' class='ui-menu ui-widget ui-widget-content' role='menu' tabindex='0' style='display: table; width: 220px; margin: 0 auto;'>\r\n";
markUp += "\t<li data-menu='job' class='ui-menu-item' id='ui-id-2' tabindex='2' role'=menuitem' style='display: inline-block; width: 220px; vertical-align: top; horizontal-align: center'><span class='ui-icon ui-icon-triangle-1-s'></span>\r\n";
markUp += "<ul class='subMenu ui-menu ui-widget ui-widget-content' id='jobMenu' role='menu' tabindex='-1' style='display: block; padding-left: 40px;'><li class='ui-menu-item' id='ui-id-5' tabindex='0' role='menuitem'><br></br>-->Tier1 VAE<br></br></li > <li class='ui-menu-item' id='ui-id-6' tabindex='1' role='menuitem'>-->Tier1 Non-VAE<br></br></li><li class='ui-menu-item' id='ui-id-7' tabindex='2' role='menuitem'>-->Tier2<br></br></li><li class='ui-menu-item' id='ui-id-7' tabindex='3' role='menuitem'>-->Tier1 Smart Conversion<br></br></li></ul></li>\r\n";
$("#startJobDialog").html(markUp);
...
</code></pre>
<p>As per above code, I am setting HTML <code>markup</code> to <code>#startJobDialog</code> and it gives me following output: </p>
<p><a href="https://i.stack.imgur.com/8VqVf.png" rel="nofollow"><img src="https://i.stack.imgur.com/8VqVf.png" alt="JS output"></a></p>
<p>As you can see, whenever I select an item in the menu list, the <code>selection checkmark</code> is coming below the selected item, but I really want it to be next to the item selected. It looks like the width is correct and I tried tweaking it. Not a JS expert, I am in initial exercises - any insights on different class, styles, and other parameters with respect to <code><ul>, <li></code>, etc. would help and I really want to make this dropdown look better than it is right now.</p>
<p>How to set that checkmark in the right/my desired position in JS and make the selection list look better?</p>
| <p>My suggestion would be to remove the css from your markup and put them in a css file.</p>
<p>From there, try absolute positioning your elements.</p>
<p>I have provided an example snippet of your code in this post, just to look at and play around with. You can see a bunch of <code><br></code>'s being added to what I would assume is the default selected item. I don't see where the checkmark is being added.</p>
<p>If you provide a snippet, I can help you further. But, floating, or absolute positioning could be an option. Or you can use the ::before or ::after pseudo selectors.</p>
<p>In order for me to be more specific I would need to see the exact markup that gets generated.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var markUp = "<ul id='topMenu' class='ui-menu ui-widget ui-widget-content' role='menu' tabindex='0' style='display: table; width: 220px; margin: 0 auto;'>\r\n";
markUp += "\t<li data-menu='job' class='ui-menu-item' id='ui-id-2' tabindex='2' role'=menuitem' style='display: inline-block; width: 220px; vertical-align: top; horizontal-align: center'><span class='ui-icon ui-icon-triangle-1-s'></span>\r\n";
markUp += "<ul class='subMenu ui-menu ui-widget ui-widget-content' id='jobMenu' role='menu' tabindex='-1' style='display: block; padding-left: 40px;'><li class='ui-menu-item' id='ui-id-5' tabindex='0' role='menuitem'><br></br>-->Tier1 VAE<br></br></li > <li class='ui-menu-item' id='ui-id-6' tabindex='1' role='menuitem'>-->Tier1 Non-VAE<br></br></li><li class='ui-menu-item' id='ui-id-7' tabindex='2' role='menuitem'>-->Tier2<br></br></li><li class='ui-menu-item' id='ui-id-7' tabindex='3' role='menuitem'>-->Tier1 Smart Conversion<br></br></li></ul></li>\r\n";
$("#startJobDialog").html(markUp);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="startJobDialog"></div></code></pre>
</div>
</div>
</p>
|
Computing average from relation with null values in SQLite <p>I'm having a hard time computing the average in SQL when I have null fields in a table. I want to include fields which have null and replace them with the number 10 before calculating the average. Suppose I have the following relation:</p>
<pre><code>x | y
-------
j | 3
k | 4
l | NULL
n | 55
</code></pre>
<p>My logic so far has been to take all the fields y where there are null values and take the sum and count of items in that table, and then take the sum and count of fields who do not have null values. From this, I combine both sums and counts and compute the average. So far I have the following query:</p>
<pre><code>SELECT sum1+sum2/c1+c2
FROM (SELECT sum(cap) as sum1, count(*) as c1 FROM courses)
UNION (SELECT SUM(null_fields) as sum2, c2
FROM (SELECT 10 as null_fields, count(*) as c2 FROM courses
WHERE cap IS NULL))
</code></pre>
<p>However, this doesn't work. Any thoughts? </p>
| <p>Use <code>coalesce()</code>:</p>
<pre><code>select avg(coalesce(cap, 10))
from courses;
</code></pre>
|
angularjs - ng-repeat inside ng-included partial not working <p>In my parent page I include a partial using ng-include. Within that partial I use a ng-repeat to echo out form elements.</p>
<p>As you can see, the array for ng-repeat has 4 items (elements.length), but for whatever reason, angularjs skips ng-repeat completely. As if the directive is disabled.</p>
<p>I use this exact same setup (ng-include a partial that has ng-repeat) in other areas of my app without any problems. For the life of me I can't figure out why this one just skips ng-repeat.</p>
<p>parent page:</p>
<pre><code><div ng-include src="'/views/form/partial.html'"></div>
</code></pre>
<p>partial.html</p>
<pre><code> <form method="post" accept-charset="UTF-8" action="{{form.url}}{{form.hash}}">
<input type="hidden" name="h" value="{{form.hash}}" />
<p>Elements: {{elements.length}}</p>
<pre>{{elements|json}}</pre>
<div ng-repeat="element in elements">
<label for="{{element.variable}}">{{element.display}}</label>
<input type="input" id="{{element.variable}}" name="{{element.variable}}" value="" />
</div>
<input type="submit" value="{{form.submit_text}}" />
</form>
</code></pre>
<p>What is rendered in the partial:</p>
<pre><code> <form method="post" accept-charset="UTF-8" action="http://weebsite.com/h/eb58f4450026eae5815cbf4742cb27cd">
<input type="hidden" name="h" value="eb58f4450026eae5815cbf4742cb27cd" />
<p>Elements: 4</p>
<pre>[
{
"variable": "email",
"mandatory": true,
"display": "Email",
"hidden": false
},
{
"variable": "first_name",
"mandatory": false,
"display": "First Name",
"hidden": false
},
{
"variable": "last_name",
"mandatory": false,
"display": "Last Name",
"hidden": false
},
{
"variable": "new_field_3335",
"mandatory": false,
"display": "New Field",
"hidden": false
}
]</pre>
<div ng-repeat="element in elements">
<label for=""></label>
<input type="input" id="" name="" value="" />
</div>
<input type="submit" value="click me now" />
</form>
</code></pre>
| <p>Turns out, ng-repeat fails inside a <code><textarea></code>, while other variable substitution works as expected.</p>
<p>The partial.html is inside a <code><textarea></code>. Once I removed it from the <code><textarea></code>, everything worked.</p>
|
Eclipse no "Design" pane? <p>Basically the issue is, that I no longer have a design tab in Eclipse. This issue appeared just now, when I was about to very happily work on some stuff.</p>
<p>I already had Swing Designer installed, and I've been working in the Design pane for a whole week. But today when I opened up Eclipse, it gave me some weird error that apparently the file was not found or the directory was missing, even thought it was right there on the screen and I could literally go to the workspace folder where the files were. So I had to delete the workspace and create a new one.</p>
<p>Trust me, I've been searching this issue for literally an hour, and every single time, the solution is right-clicking the .java file, and opening it with "WindowBuilder Editor". I've literally done this exact thing over 20 times, and no "Design" or "Source" panes on the bottom are appearing.</p>
<p>I've tried reinstalling the plugin, opening both the java and class files with "WindowBuilder Editor". Absolutely nothing works.</p>
| <p>Found the solution. Had to put the .java file in the "src" folder.</p>
|
Confusion on async file upload in python <p>So I want to implement async file upload for a website. It uses python and javascript for frontend. After googling, there are a few great posts on them. However, the posts use different methods and I don't understand which one is the right one.</p>
<p>Method 1:
Use ajax post to the backend. </p>
<p>Comment: does it make a difference? I thought async has to be in the backend not the front? So when the backend is writing files to disk, it will still be single threaded.</p>
<p>Method 2:
Use celery or asyncio to upload file in python.</p>
<p>Method 3:
use background thread to upload file in python.</p>
<p>Any advice would be thankful.</p>
| <p>Asynchronous behavior applies to either side independently. Either side can take advantage of the capability to take care of several tasks as they become ready rather than blocking on a single task and doing nothing in the meantime. For example, servers do things asynchronously (or at least they should) while clients usually don't need to (though there can be benefits if they do and modern programming practices encourage that they do).</p>
|
Angular Authentication <p>The problem is on every $routeChangeStart if user is not found it still directs me to pages if I just type the url.</p>
<p>Now I have rewrite the rules on the server.</p>
<pre><code>Options +FollowSymlinks
RewriteEngine On
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule (.*) /index.html [L]
</code></pre>
<p>And here is the app.js </p>
<pre><code>var app = angular.module('myApp', ['ngRoute']);
app.config(function($httpProvider){
// attach our Auth interceptor to the http requests
$httpProvider.interceptors.push('AuthInterceptor');
});
app.run(['$rootScope','$scope','Auth', '$location', function($rootScope, $scope, Auth, $location){
$rootScope.$on('$routeChangeStart', function(event){
$scope.loggedIn = Auth.isLoggedIn();
console.log(Auth.isLoggedIn());
Auth.getUser().then(function(response){
console.log(response);
$scope.user = response;
}).catch(function(error){
console.log(error);
});
});
}]);
</code></pre>
<p>And here is mine angular auth factory</p>
<pre><code>app.factory('AuthToken', function($window){
var authTokenFactory = {};
authTokenFactory.setToken = function(token){
if(token){
$window.localStorage.setItem('token', token);
}else{
$window.localStorage.removeItem('token');
}
};
authTokenFactory.getToken = function(){
return $window.localStorage.getItem('token');
}
return authTokenFactory;
});
app.factory('Auth', function($http, $q, AuthToken, Passingtoken){
var authFactory = {};
authFactory.login = function(email, password){
var data = {
email: email,
password: password
};
return $http.post('/loginForm.php', JSON.stringify(data)).then(function(response){
// console.log(response);
AuthToken.setToken(response.data);
return response;
}).catch(function(e){
console.log(e);
return $q.reject(e.data);
});
};
authFactory.logout = function(){
AuthToken.setToken();
};
authFactory.isLoggedIn = function(){
if(AuthToken.getToken()){
return true;
}else{
return false;
}
};
authFactory.getUser = function(){
var defer = $q.defer();
if(AuthToken.getToken()){
var userdata = JSON.parse(Passingtoken.getUserData());
userdata = userdata[0].data;
console.log(userdata);
/**
* get the token. Might make this a service that just gets me this token when needed.
*/
$http.post('/decode.php', {
userdata
}).then(function(response){
console.log(response.data.rows[0]);
//$scope.username = response.data.rows[0].fullname;
defer.resolve(response.data.rows[0]);
}, function(e){
console.log(e);
});
}else{
return $q.reject({
message: 'User not found'
});
}
return defer.promise;
};
return authFactory;
});
app.factory('AuthInterceptor', function($q, $location, AuthToken){
var interceptorFactory = {};
interceptorFactory.request = function(config){
// grab a token
var token = AuthToken.getToken();
// if token is there added to header
if(token){
config.headers['x-access-token'] = token;
}
return config;
};
interceptorFactory.responseError = function (response) {
if (response.status == 403){
AuthToken.setToken();
$location.path('/login');
}
return $q.reject(response);
};
return interceptorFactory;
});
</code></pre>
<p>And here is maincontroller where I am checking for route change</p>
<pre><code>app.controller('mainCtrl', ['$scope', 'Passingtoken', '$http','$window', 'Auth', '$location', '$rootScope', function($scope, Passingtoken, $http, $window, Auth, $location, $rootScope){
// check for loggin in
$scope.loggedIn = Auth.isLoggedIn();
// rootscope
$rootScope.$on('$routeChangeStart', function(event){
$scope.loggedIn = Auth.isLoggedIn();
console.log(Auth.isLoggedIn());
Auth.getUser().then(function(response){
console.log(response);
$scope.user = response;
}).catch(function(error){
console.log(error);
});
});
$scope.logged = function(){
if($scope.loginData.email !== '' && $scope.loginData.password !== ''){
Auth.login($scope.loginData.email, $scope.loginData.password).then(function(response){
//console.log(response);
if(response.data !== 'failed'){
Passingtoken.addData(response);
$location.path("/home");
//$window.location.reload();
}else{
}
}, function(e){
console.log(e);
});
}
};
/**
* Logout function
*/
$scope.logout = function(){
Auth.logout();
$scope.username = "";
$location.path("/");
}
}]);
</code></pre>
<p>In $rootscope.on I am checking if user has the token and if user does then route can change (I am using jwt), but if I go through url then it will take me anywhere even if I don't have the token. In my maincontroller I try to add $location.path('/') in .catch() then on every route change it will take me to that path even if I am not logged in and try to click on login it will redirect me to that path and that make sense. I am just lost on how to make sure a user cannot get in through the url and angular should just check on every request. Any help will be greatly appreciated. </p>
<p>Thank you in advance </p>
| <p>move this portion of code into your application's run block. </p>
<pre><code>$rootScope.$on('$routeChangeStart', function(event){
$scope.loggedIn = Auth.isLoggedIn();
console.log(Auth.isLoggedIn());
Auth.getUser().then(function(response){
console.log(response);
$scope.user = response;
}).catch(function(error){
console.log(error);
});
});
</code></pre>
|
Pandas timeseries resampling and interpolating together <p>I have timestamped sensor data. Because of technical details, I get data from the sensors at <em>approximately</em> one minute intervals. The data may look like this:</p>
<pre><code> tstamp val
0 2016-09-01 00:00:00 57
1 2016-09-01 00:01:00 57
2 2016-09-01 00:02:23 57
3 2016-09-01 00:03:04 57
4 2016-09-01 00:03:58 58
5 2016-09-01 00:05:00 60
</code></pre>
<p>Now, essentially, I would be extremely happy if I got all data at the exact minute, but I don't. The only way to conserve the distribution and have data at each minute is to interpolate. For example, between row indexes 1 and 2 there are 83 seconds, and the natural way to get a value at the exact minute is to interpolate between the two rows of data (in this case, it is 57, but that is not the case everywhere).</p>
<p>Right now, my approach is to do the following:</p>
<pre><code>date = pd.to_datetime(df['measurement_tstamp'].iloc[0].date())
ts_d = df['measurement_tstamp'].dt.hour * 60 * 60 +\
df['measurement_tstamp'].dt.minute * 60 +\
df['measurement_tstamp'].dt.second
ts_r = np.arange(0, 24*60*60, 60)
data = scipy.interpolate.interp1d(x=ts_d, y=df['speed'].values)(ts_r)
req = pd.Series(data, index=pd.to_timedelta(ts_r, unit='s'))
req.index = date + req.index
</code></pre>
<p>But this feels rather drawn out and long to me. There are excellent pandas methods that do resampling, rounding, etc. I have been reading them all day, but it turns out that nothing does interpolation just the way I want it. <code>resample</code> works like a <code>groupby</code> and averages time points that fall together. <code>fillna</code> does interpolation, but not after <code>resample</code> has already altered the data by averaging.</p>
<p>Am I missing something, or is my approach the best there is?</p>
<hr>
<p>For simplicity, assume that I group the data by day, and by sensor, so only a 24 hour period from one sensor is interpolated at a time.</p>
| <pre><code>d = df.set_index('tstamp')
t = d.index
r = pd.date_range(t.min().date(), periods=24*60, freq='T')
d.reindex(t.union(r)).interpolate('index').ix[r]
</code></pre>
<p><a href="https://i.stack.imgur.com/E8HOF.png" rel="nofollow"><img src="https://i.stack.imgur.com/E8HOF.png" alt="enter image description here"></a></p>
<hr>
<p>Note, <code>periods=24*60</code> works on daily data, not on the sample provided in the question. For that sample, <code>periods=6</code> will work.</p>
|
Node JS Scoping <p>There's something wrong with my scoping that I'm not quite understanding here. I have the following sample code:</p>
<pre><code>/**
* Created by David on 10/9/2016.
*/
var public = {};
//REQUIRES
var fs = require('fs');
var rl = require('readline');
//========================================
var configFile = './config';
public.configFile = configFile;
//========================================
public.readSettingsFile = function(conFile){
return new Promise(function(resolve,reject){
try {
console.log("Importing Settings");
//read configuration file line by line
var lineStream = rl.createInterface({
input: fs.createReadStream(conFile === undefined ? configFile : conFile)
});
lineStream.on('line', function (line) {
if(!line.startsWith('#')){
var splitLine = line.split('=');
switch(splitLine[0]){
case 'version':
public.version = splitLine[1];
break;
case 'basePath':
public.basePath = splitLine[1];
break;
}
}
resolve(public);
});
}catch(err){
reject(err);
}
});
}
//========================================
module.exports = public;
</code></pre>
<p>I would expect, with the promises that on the .then, p should return, after a successful readSettingsFile, that public.version should now be included, but it's returning the following:</p>
<pre><code>{ configFile: './config', readSettingsFile: [Function] }
</code></pre>
<p>The console.log in the switch statement is correctly returning:</p>
<pre><code>0.1
</code></pre>
| <p>I think your issue isn't with "scoping", but you don't understand how to use promises. I highly recommend both the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow">Mozilla documentation</a> and <a href="https://davidwalsh.name/promises" rel="nofollow">David Walsh's blog post</a>. I also recommend you start small and write some simple promises before trying something more complicated. </p>
<p>Now I'll answer your specific question. The reason you're not seeing what you want to see is that all your linestream business is asynchronous. You return the promise at the end of your function before you get to your switch statement. Basically, think of a promise as a whole function. But rather than returning a value, you're returning the promise of a value or an error. If you're throwing a promise in the middle of a function, your function is trying to do too many things and you need to separate your code out more. </p>
<p>This should be closer to what you want. This isn't perfect code, and it may not suit your needs, but hopefully it gets you on the right track. Good luck. </p>
<pre><code>public.readSettingsFile = function(conFile){
return new Promise(function(resolve, reject) {
var lineStream = rl.createInterface({
input: fs.createReadStream(conFile === undefined ? configFile : conFile)
});
lineStream.on('line', function (line) {
if(!line.startsWith('#')){
var splitLine = line.split('=');
// You don't need a switch statement for only one case
if (splitLine[0] === 'version') {
public.version = splitLine[1];
console.log(public.version);
// You actually have to resolve something
resolve(public);
} else {
// There's a problem, reject it.
reject("Some error message");
}
});
}
}
</code></pre>
|
How to run two spring boot application on a same jvm? <p>The problem is what the title has described.</p>
<p>I have googled a lot.But the solution I found are a little old and not very useful for me.</p>
<p>I want to see the demo code and know the principle.</p>
<p>Any one can help? Really Thx.</p>
| <h3>(1) Deploy 2 WARs in a web container</h3>
<p>You could build both spring boot projects as WARs and deploy them in the same web container.
Take a look at:</p>
<ul>
<li><a href="http://stackoverflow.com/a/39233933/641627">How to deploy spring-boot WAR in a container</a></li>
<li>and <a href="https://spring.io/guides/gs/convert-jar-to-war/" rel="nofollow">this spring guide</a>.</li>
</ul>
<h3>(2) Online tutorial on the matter</h3>
<p>Otherwise, take a look at this tutorial : <a href="http://www.davidtanzer.net/running_multiple_spring_boot_apps_in_the_same_jvm" rel="nofollow">http://www.davidtanzer.net/running_multiple_spring_boot_apps_in_the_same_jvm</a></p>
|
Placing form input into an ordered list with Javascript <p>I'm new to javascript. I am trying to grab the answer the user submits through the form and then place it in an ordered list in the HTML document. I know how to do this in PHP but my assignment requires me to use javascript and I'm not sure what to do after I get the element by ID. </p>
<p>Any help is wonderful, Thank you! </p>
| <p>You can do this easily by use get <code>ElementbyId.value</code>, then display by <code>innerHTML</code>.</p>
<pre><code><textarea placeholder="Type somethings..." id="input"></textarea>
<input type="button" id="btn" value="Change"/>
<div id="result" style="text-align:left"></div>
<script language="javascript"/>
var btn = document.getElementById("btn");
btn.addEventListener('click',function change(){
var text = document.getElementById("input").value;
document.getElementById("result").innerHTML=text;
});
</script>
</code></pre>
|
Matlab - Find points in vicinity <p>Lets say I have a dataset like below.</p>
<p>X = [170,85;
165,75;
180,100;
190,120;
160,80;
170,70];</p>
<p>a distance vector</p>
<p>Y = [10,20];</p>
<p>a data point</p>
<p>Z = [166,77];</p>
<p>I want to find all the points of X that fall within the distance Y from the point Z</p>
<p>Answer should be
ans = [170,85;
165,75;
160,80;
170,70]</p>
<p>How can I do this in Matlab</p>
| <pre><code>a= X(abs(X(:,1)-Z(1))<=Y(1) & abs(X(:,2)-Z(2))<=Y(2),:)
</code></pre>
<p><strong>EDIT</strong></p>
<p>Multidimensional solution can look like this:</p>
<pre><code>a= X(all(abs(X-ones(size(X,1),1)*Z) <= ones(size(X,1),1)*Y,2),:)
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.