text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How to judge the searching precision of Particle Swarm Optimization?
As the title mentioned, how can I judge the searching precision of PSO? Is this depending on the velocity of the particles? I would like to give an example to clarify my question: For a 2-D searching, the precision of grid ergodic searching is the searching step. But what the precision should be using PSO searching. From the position update formula of PSO:
$x_i \leftarrow x_i+v_i$
So, we can assume the precision of PSO searching is the maximum of velocity of particles? Is this right?
Generally, we set the maximum of particle velocity is about 10% to 20% of the position scale. But with this setting, we can still obtain a good precision with PSO, which contradicts previous assumption. So the searching precision of PSO is? Or it can be expressed as a function of maximum velocity and other parameters?
It seems that PSO can realize arbitrary precision... Because if there are sufficient particle numbers and iteration times, the PSO can approach to the actual solution.
A:
If by "precision" you mean the error in the result of PSO (i.e., the difference between the value that PSO outputs and the true global optimum), the error can be arbitrarily large. PSO is a heuristic. There are no guarantees that it finds the global optimum, or even that it gets close -- and there is no formula in terms of parameters (like velocity) for how large the error will be. The error depends on the optimization problem you're solving and on the shape of the loss surface.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to use jdk.internal.misc.Signal in java11
I've got a class that uses jdk.internal.misc.Signal.
In module-info.java there is requires jdk.unsupported.
If I try to compile this I get:
[ERROR] MyClass.java:[28,20] package jdk.internal.misc is not visible
[ERROR] (package jdk.internal.misc is declared in module java.base, which does not export it to module MyModule)
Then if I add <arg>--add-exports</arg><arg>java.base/jdk.internal.misc=MyModule</arg>
to maven-compiler-plugin:3.8.1 I get:
[ERROR] exporting a package from system module java.base is not allowed with --release
Then if I remove <release>11</release> I get:
Fatal error compiling: warning: source release 11 requires target release 11
I've the feeling that I'm missing something important or maybe it is just a bug?
I'm using maven 3.6.3 and openjdk 11.0.2.
A:
jdk.internal.misc.Signal is in java.base module. If you take a look inside its module-info.java file you will notice this:
exports jdk.internal.misc to
(...)
jdk.unsupported;
However jdk.unsupported contains sun.misc.Signal which is the original pre-Java 9 class for handling signals.
In general usage of classes in .internal. packages is a bad practice because they are not part of public API.
Instead I would suggest to use sun.misc.Signal with requires jdk.unsupported module clause until there is a @Deprecated annotation with information which API should be used instead.
BTW. This is a great example how JPMS helps with hiding internal implementation details of a library (in this case JDK) from un/intended usage.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get list of registered views in prism with MEF
Or a list of registered parts ?
tried
[Import]
CompositionContainer container;
but it failed
A:
Make sure that your Bootstrapper is exporting the CompositionContainer.
Starting with Prism's ModularityWithMef sample, I added the following to QuickStartBootstrapper : MefBootstrapper
protected override void ConfigureContainer()
{
base.ConfigureContainer();
this.Container.ComposeExportedValue<CompositionContainer>(this.Container);
}
Then I was able to access the CompositionContainer from other modules.
Also try using [Import(AllowDefault = true, AllowRecomposition = true)] to get out of dependencies.
| {
"pile_set_name": "StackExchange"
} |
Q:
Looking for a good online map with rivers
Is there any internet map source (zoomable, tiled, i.e. "google like") with good display of rivers? I.e. well labelled even on larger scales? So that I'm for example able to track Donau river (with label) on scale like this.
Basic google map is just terrible, rivers are not well displayed, often lost on larger scales, and in 90% cases not labelled.
OpenStreetMap - similar, furthermore they denote roads as blue (!!!) which is even more confusing! (really bad practice)
OpenCycleMap - even worse...
A:
With your requirements being 'google-like' I would recommend taking a look at The National Geographic basemap, available via ArcGIS Online.
Although the basemap is not designed specifically with hydrology in mind, it has more emphasis on natural terrain and also has good labelling (including rivers). Maps like Google/Bing/OSM usually have more focus on features such as urban areas and roads.
Take a look to see if it meets your needs.
Cannot be argued that National Geographic do some sexy cartography.
A:
Maybe you could do this with a custom styled google map (via http://gmaps-samples-v3.googlecode.com/svn/trunk/styledmaps/wizard/index.html) :
or you create a custom OSM map via http://maps.cloudmade.com/editor (you need a login for that).
A:
I think the best option would be to try and find a WMS service that has world rivers on it and use that in a GIS (i.e. QGIS, gvSIG, uDig etc) overlaid with other general mapping provided by either another web-service or your own local data.
Some possible starting places (I've not tested them myself) might include:
http://nowcoast.noaa.gov/wms/com.esri.wms.Esrimap/obs?service=wms&version=1.1.1&request=GetCapabilities (WMS) (which is listed as being from - http://nowcoast.noaa.gov/help/mapservices.shtml?name=mapservices)
http://atlas.nrcan.gc.ca/auth/english/dataservices/web_map_service.html
Etc. A search for "WMS world rivers" should probably work (where I got those from).
| {
"pile_set_name": "StackExchange"
} |
Q:
Incorrect syntax near 'CAST' Error while using dynamic sql
declare @sql nvarchar(max)
declare @region as nvarchar(30)
set @region = 'Region'
set @sql = N'SELECT Year, @geo,
[Segment],Age,
SUM(CAST([Units_Sold] as Float)) Total_Units,
Sum(case when [Make] ='+ 'Toyota'+ 'then CAST([Units_Sold] as float) else 0 end)
Toyota_Total_Units,
(case when SUM(CAST([Units_Sold] as float)) = 0 then' +'0'+
'else ((Sum(case when [Make] ='+ 'Toyota' +
'then CAST([Units_Sold] as float) else 0 end)/SUM(CAST([Units_Sold] as
float)))*100)
end) Market_Share
INTO #TYT_METRIC_CURRENT_GROUP FROM Toyota1 where Year =' + '2017'
+ 'Group BY
GROUPING SETS
(
(Year,@geo,[Segment],Age),
(Year,@geo,[Segment]),
(Year,@geo)
)
set @sql = replace(@sql, '@geo', @region)
exec sp_executesql @sql
ERROR
Incorrect syntax near 'CAST'.
A:
declare @sql nvarchar(max)
declare @region as nvarchar(30)
set @region = 'Region'
set @sql = N'SELECT Year, @geo, [Segment],Age, SUM(CAST([Units_Sold] as Float)) Total_Units,
Sum(case when [Make] = ''Toyota'' then CAST([Units_Sold] as float) else 0 end)
Toyota_Total_Units, (case when SUM(CAST([Units_Sold] as float)) = 0 then 0
else ((Sum(case when [Make] = ''Toyota'' then CAST([Units_Sold] as float) else 0 end)/SUM(CAST([Units_Sold] as
float)))*100)
end) Market_Share
INTO #TYT_METRIC_CURRENT_GROUP FROM Toyota1 where Year = 2017
Group BY
GROUPING SETS ( (Year,@geo,[Segment],Age), (Year,@geo,[Segment]), (Year,@geo) )'
set @sql = replace(@sql, '@geo', @region)
exec sp_executesql @sql
| {
"pile_set_name": "StackExchange"
} |
Q:
Converting decimal to binary with user input
I wanna make a c# application that convert a decimal number into binary with the input from the user. I get a red squiggly line on bin, when declaring bin = Convert.ToString(decToBin,2);. I don't understand my problem, so any help would be appreciated.
int decToBin;
Console.WrinteLine("Enter a number that will be converted to binary")
decToBin = Int32.Parse(Console.Readline());
bin = Convert.ToString(decToBin,2);
Console.ReadKey();
A:
i guess you haven't declared bin. it should be
int decToBin;
Console.WriteLine("Enter a number that will be converted to binary");
decToBin = Int32.Parse(Console.ReadLine());
string bin = Convert.ToString(decToBin, 2);
Console.WriteLine(bin);
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to convert creatures from 3.x to 4E?
I've reccently discovered a load of monsters I created for 3.x D&D and would love to convert them to 4E.
Do any guides exist for this? Or could someone give me the most important points to remember when re-creating a monster into 4e?
A:
Take a page from Robert J. Schwalb.
He's systematically updating monsters from the epic level handbook to 4e. The essence is to ignore the mechanics, and preserve a subset of the unique iconic attacks.
Use the 4e monster creation rules in the DMG with appropriate damage and defense updates from errata. A handy javascript cruncher is here.
Generally you want a few iconic powers, rather than a lot of fiddly powers. The best way to learn is through memisis of Schwalb.
A:
Focus on rebuilding a monster using 4e rules, not converting it. Most monsters in 3E are over-engineered to an extent, in that they have many more things in their statblock than players will ever see during the game. The basic rules for creating 4e monsters can be found in the DMG.
Decide what the one or two defining features of a monster are, and create powers that reflect that. E.g. A phase spider can teleport. Make sure it has a utility power that allows her to teleport, and maybe create an attack that includes teleportation as 'for free'.
Don't worry if you don't capture every feature, or if the monsters seem 'easy' compared to their 3.5 counterpart - it's ok that a 4e medusa only gets to petrify (save ends).
What I usually do is to also create an encounter location for the monster that works well with 4e rules - as 4e puts a lot of emphasis on placement during the battle, think about how the defining monster feature mentioned above interacts with the environment.
The phase spider is best utilized in a place where spider webs hinder movement, and the medusa is more memorable and dangerous if there is unstable ground or dungeon traps that move petrified player characters into less optimal positions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Will all perl versions support older modules?
I'm have Perl 5.8 installed on all of our servers and wanted to use the DBI and DBD::Oracle modules to access our databases. My main concern is with the newer versions of perl the DBI and DBD modules will stop working with 5.8. Then I'd have to upgrade every server to the newest perl version.
My question is as perl itself becomes later versions and modules are developed for them will they still be backwards compatible? "CPAN does not carry all ancient releases and patchlevels of Perl", if I create documentation saying run "cpan -i DBI" if the newest version of DBI will not function with 5.8?
A:
There is no guarantee.
In general, you want to use the same versions of the modules on all your systems. If you use different versions then you will have different bugs and features available on different servers.
I'd suggest creating Debs / RPMS / etc for the ones you are going to use and then run a package repository that all your servers share.
A:
In general, no. There are a lot of great new features in recent releases of Perl (smart match operator, the // operator, for two one example) that are not backwards compatible. Many authors will decide to take advantage of these features rather than keep their modules compatible with older versions of Perl.
Check the CPAN Tester's Matrix of a module, including the link about the max version that passes all of the distribution's tests, to get an idea of what versions of Perl are compatible with each version of a module.
cpan -i Some::Module will indeed attempt to install the latest version of the module Some::Module, but with a little research, it can be used to install older versions too. You need to find or guess the author of an older version and provide the path to the distribution on the CPAN mirror servers. For example,
cpan -i J/JF/JFRIEDL/Yahoo-Search-1.9.12.tar.gz
cpan -i A/AS/ASG/List-Gen-0.80.tar.gz
CPAN authors may delete their older distributions from CPAN. But even then, the distribution is available at the BackPAN if you're willing to download, unpack, and build the distribution yourself.
A:
Not absolutely, but in general perl is pretty gentle about breaking code, with not many breaking changes, and long deprecation cycles on the ones that do happen. A pretty hefty portion of the code that was uploaded to CPAN in 1999 will run without modification in perl 5.14.
Since perl 5.12, the perl release cycle has become shorter, and the deprecation periods have also become shorter, which is cause for concern, but at the same time the concept of feature versioning has gained currency. The idea is that code may declare the version of perl that it's targeting with use VERSION (e.g. use 5.16.0), and any code that doesn't declare a version is assumed to be targeting approximately 5.10. When code that targets an older perl version is run on a newer perl version, newer features that might cause compatibility issues (e.g. new keywords) are disabled, and old misfeatures may be re-enabled in the name of compatibility. This isn't an absolute guarantee, but it will be adhered to as much as practical.
More information about back-compatibility and deprecation is in perlpolicy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Elastic Search - Pagination on Aggregations
I have an index and I query an aggregation, instead of returning the whole aggregation at once I want to have it returned in chunks, that is small small blocks, is it possible to do so in Elastic Search?
A:
Try to use Bucket sort
POST /sales/_search
{
"size": 0,
"aggs" : {
"sales_per_month" : {
"date_histogram" : {
"field" : "date",
"interval" : "month"
},
"aggs": {
"total_sales": {
"sum": {
"field": "price"
}
},
"sales_bucket_sort": {
"bucket_sort": {
"sort": [
{"total_sales": {"order": "desc"}}
],
"size": 3,
"from": 10
}
}
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
MMO Server functionality in Unity3D
I've created a multiplayer server for Unity that works like this:
Every client/player connects to the server and says 'hi'.
Server accepts the player and adds him to the players online list.
Every client start sending his position.
Server listens for client's positions and X times per second sends them to all other players online.
This is made by one bucle on all online players, so the server is configured to send say 10 times per second the updated positions to all the players.
Every client listens the server for other players position. When the server says "this player just said he's there", the client moves him there.
With this basic system, I can create a multiplayer game with Unity easily (already did it). But what if there's more than a couple of thousand players online? Then, say that every player sends his position to the server about 10times/sec. And the server has to send those position to all players around, say 100m. So, the server would run a loop for all online players (2000) comparing his position with the all 1999 players and if it's less than a 100m, send the position to the player. Or, maybe better, save all the players updated position in one array and send it to the player. (Only one message every 10s to the player should be better than hundreds, right? Anyway, the loop has to go through 2000*1999 10 times per sec, that could be painful..
I want to use Unity3d as client, I don't want to hold any physics on the server because using the unity's physics engine is good/fast/easy to work with. And I think it could be enough, maybe do some anti-cheating checking on the server-side just to get rid of badplayers.
Now, the questions :)
How does a proper mmo server work? Does every player send its position to the server X times per second and it goes through that HEAVY loop and sends his position to all players around? what about performance?
I would implement a prediction system for the next move and interpolate the current position wit the updated one received from the server. is it right?
If I have to detect player collisions with each other or with objects (bullets and more) would you do it on the client-side? or implement a players-player & player-object collision detection system in the server side and do it in the big loop?
If the player moves is with the keyboard so it doesn't have just a single position to go, how would you send the position to the server, like 10times per second and interpolate the position received by other players to create a smooth movement?
If the movement of the players is by setting force physics to them, like when you go forwards it's because there's a strength pushing you, how would you transmit this information to the other clients? Send just the position to the server and it sends it to the other players? But then, the physics would look weird... The plan b) I thought of is to send the force used to the server and every clients applies the force received by the server to all the players around them, physics here would look awesome but maybe there's a latency problem... Would it be good to use this system and send the exact position every X time? say .5s?
Well, I think this is all! I hope this post can be useful for other indies!
A:
I won't try to answer all your questions, sorry. It would be too long answer. Seems like you need to read a lot of stuff about game physics.
Shortly, if you have large number of online players you need to start thinking about server cluster and scaling. There're two main approaches:
Instances: you have multiple copies of your virtual world/map each handled by separate physical hardware with a hard limit of maximum number of players. Then you start reading about matchmaking.
"Shared universe": split your world to sectors each handled by separated physical hardware. Much more challenging to implement. Can support seamless world.
You can find tons of useful info on www.gamedev.net.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I convert close Longitude/Latitude points to drawable x/y coordinates in Java?
I'm having trouble converting latitude and longitude coordinates to X/Y coordinates that are suitable for drawing to a JPanel. I can convert them to proper x/y values, however these values are all far too similar and don't differ by enough to actually draw the map I'm trying to draw. I'm using a JPanel with Line2D's, however I've seen examples that use a Polygon but when I did this the map didn't look correct at all.
The lat/long points that I convert are all very close (all lie within a college campus), so my x/y values are also very close. I need a way to conver them so that they are represented in a 600x600 pixel JPanel. Here's an example of some points I convert to XY and their values:
GL 43.130480 -77.631559
i2 43.130425 -77.631532
i3 43.130335 -77.631760
--Convert to X/Y--
0 GILBERT-LONG [lat=579.9952509893145, long=502.4890740637273]
44 i2 [lat=579.9950131035996, long=502.4888664711529]
45 i3 [lat=579.997021932372, long=502.48852677421297]
Here's my code for conversion, taken from another thread on here, where MAP_HEIGHT and MAP_WIDTH are both 600:
public static void toXY()
{
for(Vertex x : vertices)
{
double xVal = (x.coordinate.latitude*MAP_HEIGHT/180) + (MAP_HEIGHT/2);
double latRad = x.coordinate.longitude*(Math.PI/180);
double mercatorN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
double yVal = (MAP_HEIGHT/2)-(MAP_WIDTH*mercatorN/(Math.PI*2));
//double yVal = (x.coordinate.longitude * MAP_WIDTH/360.0) + (MAP_WIDTH/2);
x.coordinate.longitude = xVal;
x.coordinate.latitude = yVal;
}
I also multiply the x and y's by a scaleFactor that is calculated by finding the min/max's of the X and Y values and finding the ratio of the width/heigh to the different of the max and mins like this:
double scaleX = (MAP_WIDTH-20) / (maxX - minX);
double scaleY = (MAP_HEIGHT-20) / (maxY-minY);
A:
In the final step, in order to transform the xVal value which is between xMin and xMax into a value between 0 and MAP_WIDTH-20, you need something like this:
double newX = (xVal - minX) * (MAP_WIDTH-20) / (maxX - minX);
double newY = (yVal - minY) * (MAP_HEIGHT-20) / (maxY - minY);
or (using scaleX and scaleY that you defined):
double newX = (xVal - minX) * scaleX;
double newY = (yVal - minY) * scaleY;
| {
"pile_set_name": "StackExchange"
} |
Q:
PolarPlot with Dashed and PlotRange freezes for simple function
When I plot
PolarPlot[1/(1+Cos[6-t]), {t,0,2\[Pi]}, PlotRange->{{-4,4},{-4,4}}, PlotStyle->Dashed]
everything works normally, but when I change the numerator to 2,
PolarPlot[2/(1+Cos[6-t]), {t,0,2\[Pi]}, PlotRange->{{-4,4},{-4,4}}, PlotStyle->Dashed]
this causes Mathematica to freeze and have to kill the process. Any idea what is going on?
I'm using 10.0.0 on Linux, but I had the same issue with 10.0.0 OSX.
If I take away the PlotStyle, it works. If I take away PlotRange, it works. If I change Cos[6-t] to Cos[t], it works.
A:
Too long for a comment and maybe just an observation.
I'm on 10.0 for Mac OS X x86 (64-bit) (September 10, 2014) and have also a kind of freeze, the rainbow shell comes up and rotates for 10-15 seconds. This effect again fetches 3-5 times. Very uncomfortable ...
But if I set PlotRange -> 4 and Performance Goal -> "Speed" I have not freeze at all.
PolarPlot[1/(1 + Cos[6 - t]), {t, 0, 2 \[Pi]}, PlotRange -> 4,
PlotStyle -> Dashed, PerformanceGoal -> "Speed"]
PolarPlot[2/(1 + Cos[6 - t]), {t, 0, 2 \[Pi]}, PlotRange -> 4,
PlotStyle -> Dashed, PerformanceGoal -> "Speed"]
| {
"pile_set_name": "StackExchange"
} |
Q:
Yii framework: how to check whether checkbox is checked?
I want always show additional fields when chceckbox is unchecked and always hide when is checked.
I have checkbox:
<?php echo $form->checkBox($model2, 'ignore', array('onChange'=>'javascript:toggleUser2()')); ?>
js script:
<script>
function toggleUser2() {
if($('.User2_ignore').is(':checked')) {
$('.user2').hide();
} else {
$('.user2').show();
}
}
toggleUser2();
</script>
This always return false:
console.log($('.User2_ignore').is(':checked'));
I also tried attr('checked') and val(), but they are returnig 'undefined'. Is there any way to check checkbox is checked or no?
A:
Try Using this Jquery Code as shown below
$(document).ready(function(){
$("input[type=checkbox]").change(function(){
if($(this).is(":checked")){
alert("Checked");
//$(this).siblings("input[type=checkbox]").removeAttr("checked");
}else{
alert("Unchecked")
}
});
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Generated UI doc not honoring JsonProperty value using Swashbuckle AspNetCore
I have created a class that I want to use for sending in sorting and pagination information to apply to my large collections. I have a .NET Core Web API service that will receive requests and take my object as input FromQuery. I wanted to adhere to certain naming conventions (i.e. Microsoft Rest API Guidelines) for the parameter names such a $orderby, $top, $skip, etc. and have annotated the properties of the class using JsonProperty.
However, in generated swagger doc these simply just show as the property name itself which is a problem in cases where my property is named Take for example but the request parameter should be $top. I would like the generated docs to match to not cause any confusion for consumers of the API. Everything I read seems to indicate this should work and I'm stumped why its not for me.
Here is my class with the annotations using Newtonsoft.Json.JsonPropertyAttribute
[JsonObject]
public class QueryParams {
[JsonProperty( "$orderBy" )]
public string OrderBy { get; set; }
[JsonProperty( "$skip" )]
public int? Skip { get; set; }
[JsonProperty( "$top" )]
public int? Take { get; set; }
[JsonProperty( "$maxpagesize" )]
public int? MaxPageSize { get; set; }
[JsonProperty( "$count" )]
public bool? IncludeCount { get; set; }
}
And then for example my Web API action method would look something like this
[HttpGet( "type/{type}" )]
public async Task<IActionResult> GetByType(
string type,
[FromQuery]QueryParams parameters )
{
/* ... */
}
I have tried several things such as trying to use MapType as noted at
Override Schema for Specific Types but just don't have any luck. Appreciate any insight anyone can give in regards to this.
A:
According to this GitHub issue, the JsonSerializer isn't used to bind to a class for GET requests. You need to customise the model binding instead.
So, when you use a class to represent query parameters, the JsonSerializer isn’t involved. Instead, MVC model binding is used to assign values directly from the request into the instance properties.
So, if you want to be explicit about required casing for this behavior, and hence the generated description, you need to customize the model binding behavior too. I’m not at my laptop now but off the top of my head, I think you can annotate properties with “FromQuery” and set the bind name that way.
The following should work, if I understand the discussion in the GH issue correctly:
public class QueryParams {
[FromQuery( Name = "$orderBy" )]
public string OrderBy { get; set; }
[FromQuery( Name = "$skip" )]
public int? Skip { get; set; }
[FromQuery( Name = "$top" )]
public int? Take { get; set; }
[FromQuery( Name = "$maxpagesize" )]
public int? MaxPageSize { get; set; }
[FromQuery( Name = "$count" )]
public bool? IncludeCount { get; set; }
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get numbers from a string in JavaScript
I have a variable which it contains a telephone number in a sentence, to know it better it is like this "tel": "Tel: 01.78.99.93.06", now I need to get just numbers and put in another variable the out put should be like this var nom="0178999306".
How I can do it with jQuery and JavaScript?
Appreciate very much
A:
The simplest and the most robust method would be to remove all non-numerical values from the string which can be done using a simple regex:
var tel = "Tel: 01.78.99.93.06";
var nom = tel.replace(/\D/g, '');
console.log(nom);
| {
"pile_set_name": "StackExchange"
} |
Q:
IBM XSeries 335 Timeout?
I have an IBM XSeries 335 1U Server. It was given to me. It uses a special cable for display, mouse and keyboard.
I boot the OS, everything is fine for a while and then at some point the display goes blank and I cannot do anything with with the keyboard and mouse and the display does not come back.
The machine is working, I can see hard drive activity, The display light is 'green' (not orange like typical display sleep). Pressing a key on the keyboard does nothing, neither does the mouse.
How can I get my display back so I can see what is going on?
A:
The reason for the special cables is so that you can daisy-chain a load of servers together and only need one monitor and keyboard etc - a built in KVM as it were.
There should be a button on the front somewhere, which is used to select that server to be the one used by the display and input. Next to it should be an indicator LED with the general 'monitor' symbol, and this should be green. Try pressing this button if you are having problems, although I never had to use it when only connected to a single server - I've never seen this problem myself
| {
"pile_set_name": "StackExchange"
} |
Q:
Consolas Font In Vista And Windows 7
I have downloaded the Consolas font from Microsoft and installed it on my Windows Vista box. Consolas is also present on my Windows 7 box. When I use PuTTY, being sure to use the same settings on both machines, the Windows 7 box can render Unicode line/box drawing characters in Consolas, but the Windows Vista box cannot.
What is the relevant difference between them? If Consolas has the characters, why would they only appear on one system, and not on the other? I am logging into the same remote host each time, and I have been very carefully checking PuTTY's settings to make sure that they're the same on both machines.
How can I make Consolas render Unicode line-drawing characters on Vista?
A:
Microsoft modified Consolas with Windows 7 to include the line drawing characters. The reason you don't see them on your Vista system is that the version of Consolas you have installed simply doesn't contain those characters.
To get the line/box characters to show up on your Vista system, copy the Consolas font from your Windows 7 system.
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex to find whole words
How would I find if a whole word, i.e. "EU", exists within the String "I am in the EU.", while not also matching cases like "I am in Europe."?
Basically, I'd like some sort of regex for the word i.e. "EU" with non-alphabetical characters on either side.
A:
.*\bEU\b.*
public static void main(String[] args) {
String regex = ".*\\bEU\\b.*";
String text = "EU is an acronym for EUROPE";
//String text = "EULA should not match";
if(text.matches(regex)) {
System.out.println("It matches");
} else {
System.out.println("Doesn't match");
}
}
A:
Use a pattern with word boundaries:
String str = "I am in the EU.";
if (str.matches(".*\\bEU\\b.*"))
doSomething();
Take a look at the docs for Pattern.
| {
"pile_set_name": "StackExchange"
} |
Q:
Подскажите в чём ошибка, не запускается app react после закрытия
Запуская в виртуальной машине Ubuntu, через командную строку создал проект (create-react-app), запустил написал немного кода, затем закрыл редактор кода, браузер и виртуальную машину. На следующий день запускаю виртуальную машину, захожу в ком. строку (в нужную папку с проектом) прописываю npm start и вылетает ошибка (прикреплённая), приходится удалять модули и выполнять заново install, и так каждый раз, поработал ушёл на след. день ошибка. Возможно нужно как то останавливать запуск сервера или что-то где-то сохранять\выключать? Подскажите в чём дело?
Спасибо.
A:
Если watch вылетает с ошибкой ENOSPC, то скорее всего Вам поможет:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
По умолчанию в большинстве дистрибутивов лимит fs.inotify.max_user_watches для разработчиков слишком мал.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I use reflection to map a list that include enum values
If I have an object
public class Car {
public List<UpdatePart> updatePartList {get; set;}
}
public class UpdatePart {
public PartToModify PartToModify {get; set;}
public string NewValue {get;set}
}
And the PartToModify is an enum:
public enum PartToModify {
Engine,
Tire,
}
And I have a Part object:
public class Part {
public string Engine {get;set;}
public string Tire {get;set;}
public decimal price {get;set;}
}
How can I use reflection and for every property on Part that matches a enum in PartToModify, create a new UpdatePart object and select the correct enum where PartToModify == Part.Property and assigns the UpdatePart.NewValue the value of Part.Property.
I would something like:
var partProperties = partObj.GetType().GetProperties();
foreach (var property on updatePartProperties) {
UpdatePartList.Add(MapProperties(partProperties, part));
}
public UpdatePart MapProperties(PropertyInfo partProperties, Part partObj){
//pseudo code
var updatePart = new UpdatePart();
foreach(var property on partProperties) {
if (property.Name == <iterate through enum values until one is found>)
updatePart.PartToModify = PartToModify.<somehow select value that matches property.name>
updatePart.NewValue = property.GetValue(partObj, null);
}
return updatePart;
}
Obviously you get the jiff of what I am trying to do, any thoughts? And no, this is not a school project. The whole "car" example was the quickest closest example I came up with to the actual objects, since I didn't want to just write out what I was trying to accomplish, wanted to provide an example.
A:
var partNames=Enum.GetNames(typeof(PartToModify));
var parts = from pi in partObj.GetType.GetProperties()
where partNames.Contains(pi.Name)
select new UpdatePart {
PartToModify = (partToModify)Enum.Parse(typeof(PartToModify),pi.Name),
NewValue=pi.GetValue(partObj,null)
};
foreach (var part in parts) UpdateList.Add(part);
| {
"pile_set_name": "StackExchange"
} |
Q:
WIF and passive federation, cookie access
Concerning passive federation, I'm wondering how the transport of the security token from STS to the relying party works exactly.
On nearly every article regarding the Windows Identity Foundation and passive federation it is said that browser redirects (is it by the way a 30x http code?) and cookies are the only "tools" that are used.
But: when the STS stores the token in a cookie and redirects the browser to the relying party after that, how is it possible that the relying party can read this cookie? Isn't there something like a same origin policy for cookies (like javascript has it)? The issuer of the cookie (STS) is another address/source/domain than the relying party, is the relying party nonetheless allowed to access this "foreign" cookie or is it some magic in the background that makes tis possible?
Thank you
A:
The STS doesn't send a cookie, it would be impossible.
Rather, the STS returns to your browser a page containing:
a) the SAML token in the page body (XML)
b) the action=Relying Party url + the javascript to autosubmit the form
The browser happily submits such form to the relying party. It is then responsible for creating the authentication cookie used to authenticate consecutive requests from the client.
There's no "magic", just a SAML token passed explicitely in the request body. The token is signed by the STS certificate so the RP can validate its authenticity.
| {
"pile_set_name": "StackExchange"
} |
Q:
AS3 - Frame inside of a movie clip inside of a movie clip?
this might not make much sense but here we go. I have a movie clip (Player) and inside of that I have some frames that hold movie clips. Inside of those is an animation sequence. I wish to play certain ones on actions in AS3. So it's like this. Frame > Player(MovieClip) > Frame...Frame > playerDownBlock(MovieClip) > Frame...Frame. I wish to play the final frames in the final movieclips if I can. Is this possible?
Here is my set-up.
Layout/ Path of movieclips
I've attempted to do it by using this line.
Player.playerDownBlock.gotoAndPlay("playerDownBlock");
// Or
Player.gotoAndPlay("playerDownBlock");
None of these work and I don't know if I can even do it. Any help would be fantastic!
A:
All you have to do is:
mc.mc2.play();
With "mc" being the instance name of the first outside Movie Clip and "mc2" being the instance name of the inside Movie Clip.
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple Propositional Logic Explaination?
In this example, the prof states that "$Q \to R$ doesn't depend on the assumption $Q$ so he can discharge it, but without assumption $Q$, he couldn't have concluded with $Q\to R$ so the answer still depends on the assumption $Q$?
Doesn't a discharged assumption means you don't need that assumption and the proof still works??
A:
Before that final inference you had a proof of $R$ from the (undischarged hypotheses) $P$, $Q$, and $(P\wedge Q)\to R$.
But after that final inference, the conclusion of the proof is no longer $R$, but $Q\to R$. If you think about what a conditional means, we never need to assume $Q$ in order to prove $Q\to R$, since $Q\to R$ will automatically hold whenever $Q$ is false.
Another way to think about it is that we don't need to assume anything about $Q$ to get to this conclusion, since the requirements about $Q$ are now explicitly coded in the formula $Q\to R$.
Finally, you can think of it this way: If $Q$ is false, then $Q\to R$ holds trivially. If $Q$ is true, then you can apply the subproof whose conclusion was $R$ in order to prove $R$. Thus $Q\to R$ holds (assuming the other undischarged hypotheses in the proof).
| {
"pile_set_name": "StackExchange"
} |
Q:
Undo Manager stack seems to get corrupted when undoing a paste operation
I'm using undomanager and trying to implement a cut/copy/paste functionality on a doubly linked list. First, here's my code.
Karma Test Script:
it('should cut and paste a node with working undo/redo', function () {
var list = listFactory.createList();
var node1 = list.appendNode(
nodeFactory.createNode({
//nodeinfo
})
);
var node2 = list.appendNode(
nodeFactory.createNode({
//nodeinfo
})
);
// here we cut the node2 out of the profile
list.cutNode(node2.id);
expect(list.clipboard.id).toBe(node2.id);
expect(list.getLength()).toBe(2);
// undoing the cut should clear the clipboard and return the node2 to where it was.
list.undo();
expect(list.clipboard).toBe(null);
expect(list.getLength()).toBe(2);
// redoing the cut should remove node2
list.redo();
expect(list.clipboard.id).toBe(node2.id);
expect(list.getLength()).toBe(1);
// pasting node2 in front of node1
list.pasteNode(indexSeg.id);
expect(list.getLength()).toBe(2);
// the first undo should remove node2 from the front
list.undo();
expect(list.getLength()).toBe(1);
// this should reset the list back to its original state
list.undo(); // THIS COMMAND FAILS
});
List Object with Functions
var List = function () {
this.clipboard = null;
this.head = null;
this.tail = null;
this.head.next = tail;
this.tail.prev = head;
// blahblah typical linked list stuff
};
// Inserts a node in front of the node with nodeId
List.prototype.insertNode = function(node, nodeId) {
this.insertAt(node, nodeId);
var list = this;
this.undoManager.add({
undo: function() {
list.deleteNode(newNode.id);
},
redo: function() {
list.insertNode(node, nodeId);
}
});
return node;
};
// put node at tail
List.prototype.appendNode = function(node) {
this.insertAt(node, null);
var list = this;
this.undoManager.add({
undo: function() {
list.deleteNode(node.id);
},
redo: function() {
list.appendNode(node);
}
});
return node;
};
// delete node with nodeId
List.prototype.deleteNode = function(nodeId) {
var nextId = this.getNextNodeId(nodeId); // returns null if nodeId is at tail
var deletedNode = this.deleteById(nodeId);
var list = this;
this.undoManager.add({
undo: function() {
//special case for handling last node
if(!nextId)
list.appendNode(deletedNode);
else
list.insertNode(deletedNode, nextId);
},
redo: function() {
list.deleteNode(nodeId);
}
});
return deletedNode;
};
// Removes the node with nodeId from list and stores it in clipboard
List.prototype.cutNode = function (nodeId) {
var nextNodeId = this.getNextNodeId(nodeId); // returns null if nodeId is tail
var cuttNode = this.deletedNode(nodeId);
var oldClipboard = this.clipboard;
this.clipboard = cuttNode;
var list = this;
this.undoManager.add({
undo: function() {
if (!nextNodeId) {
list.appendNode(cuttNode);
} else {
list.insertNode(cuttNode, nextNodeId);
}
list.clipboard = oldClipboard;
},
redo: function() {
list.cutNode(nodeId);
}
});
};
// duplicate node with nodeId and store in clipboard
List.prototype.copyNode = function (nodeId) {
var node = this.
var oldClipboard = this.clipboard;
// duplicate() copies the node data to a new node object which generats a new/unique node id
this.clipboard = node.duplicate();
var list = this;
this.undoManager.add({
undo: function() {
list.clipboard = oldClipboard;
},
redo: function() {
list.clipboard = node;
}
});
};
// pastes clipboard node to list before nodeId
List.prototype.pasteNode = function (nodeId) {
if (this.clipboard !== null) {
var pastedNode = this.insertNode(this.clipboard, nodeId);
// just in case we want to paste again, we need a unique node
this.clipboard = pastedNode.duplicate();
var list = this;
this.undoManager.add({
undo: function() {
list.clipboard = list.deleteNode(pastedNode.id);
},
redo: function() {
list.pasteNode(nodeId);
}
});
}
};
The last undo command in the karma test fails with the following error:
Error: Unable to delete node with id 14914926779057942
This node id belongs to the duplicated node from the paste operation: this.clipboard = pastedNode.duplicate()
The undo manager calls deleteNode from the pasteNode undo function on the id of the duplicated node, rather than the pastedNode. Since the duplicated node exists only in the clipboard and not in the linked list, it errors out.
Am I not understanding the undo/redo stack correctly? What is the correct way to write cut/copy/paste?
A:
The problem here was that the undo manager's undo and redo stack were being double-stacked when the paste function called insertNode.
For example, calling cutNode would call deleteNode, which would throw a command on both the undo and redo stack. Then cutNode would add another layer on to both stacks after deleteNode returned.
I discovered the double-stacking by using UndoManager's getIndex() function in between calls to cut, copy, and paste.
| {
"pile_set_name": "StackExchange"
} |
Q:
Constant reset of full-speed USB device using ehci-pci
Running 14.04.3 Ubuntu Desktop on old HP 8510w laptop with USB 2.0 ports only.
Hi, looking at /var/log/syslog or executing dmesg | tail yields the same warning on the constant reset of USB device 008, which apparently is a parallel port.
$ dmesg | tail
[13820.044078] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13823.116151] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13825.419253] [UFW AUDIT] IN= OUT=lo SRC=127.0.0.1 DST=127.0.0.1 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=727 DF PROTO=TCP SPT=40729 DPT=9058 WINDOW=43690 RES=0x00 SYN URGP=0
[13825.419268] [UFW AUDIT] IN=lo OUT= MAC=00:00:00:00:00:00:00:00:00:00:00:00:08:00 SRC=127.0.0.1 DST=127.0.0.1 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=727 DF PROTO=TCP SPT=40729 DPT=9058 WINDOW=43690 RES=0x00 SYN URGP=0
[13825.932046] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13828.236068] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13829.566026] [UFW ALLOW] IN= OUT=eth0 SRC=192.168.1.36 DST=76.74.178.246 LEN=60 TOS=0x00 PREC=0x00 TTL=64 ID=14119 DF PROTO=TCP SPT=41592 DPT=8080 WINDOW=29200 RES=0x00 SYN URGP=0
[13831.052112] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13834.124069] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
[13836.940083] usb 2-3.1.2: reset full-speed USB device number 8 using ehci-pci
$ lsusb | grep "Device 008"
Bus 002 Device 008: ID 067b:2305 Prolific Technology, Inc. PL2305 Parallel Port
EDIT:
From the Prolific Tech's website:
The PL2305 integrated circuit provides a bi-directional bridge between
the Universal Serial Bus (USB) system and IEEE-1284 parallel port
printers.
I am not sure whether this is in any way the symptom of a USB port failing or whether it is rather a hardware problem of the USB to parallel port converter cable itself.
Can somebody help with a solution if there is one ? Tx.
A:
Bad hardware or outdated hardware EEPROM's firmware is the answer.
I had noticed that printing over USB cable stopped working in October 2015. It was not a screaming issue since I had configured my network so network printing was possible from any network device.
It turns out my Prolific Technology, Inc. PL2305 Parallel to USB port bridging cable I used for an HP LJ4 Plus printer is equipped with a single chip that does not coexist well with something (kernel side ?) on my Ubuntu 14.04.3 Desktop OS. [3.16.0-50-generic #67~14.04.1-Ubuntu x86_64]
Disconnecting the cable suppresses the message completely.
Manufacturer says reconfiguring the EEPROM is possible. I will be investigating... but this falls outside the scope of the question or AU for that matter.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to get the objects from an observable collection?
I don't know if it's possible but I would like to add objects to an observable collection and reuse them later.
I have this in wpf:
<CheckBox Margin="0,9,0,5" IsChecked="{Binding Prise1.Monday, Mode=TwoWay}"/>
<CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise2.Monday, Mode=TwoWay}"/>
<CheckBox Margin="0,10,0,5" IsChecked="{Binding Prise3.Monday, Mode=TwoWay}"/>
<CheckBox Margin="0,9,0,0" IsChecked="{Binding Durée.Monday, Mode=TwoWay}"/>
For all days of the week.
Class WeekValues :
private bool _Monday;
public bool Monday
{
get
{
return _Monday;
}
set
{
_Monday = value;
RaisePropertyChanged(nameof(Monday));
}
}
private bool _Tuesday;
public bool Tuesday
{
get
{
return _Tuesday;
}
set
{
_Tuesday = value;
RaisePropertyChanged(nameof(Tuesday));
}
}
private bool _Wednesday;
public bool Wednesday
{
get
{
return _Wednesday;
}
set
{
_Wednesday = value;
RaisePropertyChanged(nameof(Wednesday));
}
}
private bool _Thursday;
public bool Thursday
{
get
{
return _Thursday;
}
set
{
_Thursday = value;
RaisePropertyChanged(nameof(Thursday));
}
}
private bool _Friday;
public bool Friday
{
get
{
return _Friday;
}
set
{
_Friday = value;
RaisePropertyChanged(nameof(Friday));
}
}
private bool _Saturday;
public bool Saturday
{
get
{
return _Saturday;
}
set
{
_Saturday = value;
RaisePropertyChanged(nameof(Saturday));
}
}
private bool _Sunday;
public bool Sunday
{
get
{
return _Sunday;
}
set
{
_Sunday = value;
RaisePropertyChanged(nameof(Sunday));
}
}
}
And i want to do something like this:
public ObservableCollection<WeekValues> allPrises = new ObservableCollection<WeekValues>();
Prise1 = new WeekValues();
Prise2 = new WeekValues();
Prise3 = new WeekValues();
Durée = new WeekValues();
allPrises.Add(Prise1);
allPrises.Add(Prise2);
allPrises.Add(Prise3);
allPrises.Add(Durée);
And use a method like :
MyMethod(allPrises)
{
foreach(var X in allPrises)
{
if(Prise1.Monday) ...do something
if(Prise2.Monday) ... do something else
}
Is this clear?
So that's the idea, I'd like to know how to proceed, because when I make a foreach I only get trues / falses without "Prise1" or "Prise2".
Would you know how to solve this?
Thank you in advance
A:
You are iterating over all 4 WeekValues. So X is Prise1 in the first iteration and so on.
if (Prise2.Monday) could be written as if (allPrises[1].Monday) if you never change the order of the elements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Array List action listener
Hello I was trying to add action listener to array of string so
Is it possible to add onclicklistener to an ArrayList of Strings? If possible can you tell me how please.
Thank you
A:
If your ListView has more than one TextViews use something like this to retrieve the data
list.setOnItemClickedListener(new OnItemClickedListener() {
AdapterView<?> parent, View view, int position, long id){
Textview i1 = view.findViewById(R.id.t1);
Textview i2 = view.findViewById(R.id.t2);
String text = i1.getText()+i2.getText();
}
} ;
| {
"pile_set_name": "StackExchange"
} |
Q:
Handling button click events from second page to determine outcomes in first page, Ionic
I am using the Ionic Framework to build my app and I have used navPush and navPop to control navigation between two pages, and I have been able to send parameters from the first page to the second page using navPush. However, I am not really sure how to handle a button click that would not only pop back to the previous page (First Page) but also causes some features to run on the first page. For example, if you were to press the map button on the (Second Page), it will then show the polyline on the map page (First Page) between current location and the marker that was chosen. I already have the functionality for showing a polyline between a marker and current location, is there a way to pop back to the First Page with the marker chosen and a command to call a specific function?
SecondPage.ts:
import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, Navbar} from 'ionic-angular';
import { CallNumber } from '@ionic-native/call-number';
import { Toast } from '@ionic-native/toast';
/**
* Generated class for the ListPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-list',
templateUrl: 'list.html',
})
export class ListPage {
@ViewChild(Navbar) navBar: Navbar;
places: any = [];
constructor(public navCtrl: NavController, public navParams: NavParams,
private callNumber: CallNumber, private toast: Toast) {
this.places = [];
}
ionViewDidLoad() {
this.navBar.backButtonClick = (e:UIEvent)=>{
this.navCtrl.pop({animate: true, animation: "transition", direction: "down", duration: 300});
};
this.places = this.navParams.get('places');
this.places.sort(function(a, b) {
return parseFloat(a.distance.substring(0, a.distance.indexOf(' ')))
- parseFloat(b.distance.substring(0, b.distance.indexOf(' ')))});
}
phoneDial(phone_number) {
this.toast.show("Calling Number.", '3000', 'center');
this.callNumber.callNumber(phone_number, true);
}
}
A:
I was able to figure it out, here is a good link to a tutorial that helped me to figure it out: https://alligator.io/ionic/events/, I hope this helps others developing with the ionic framework.
| {
"pile_set_name": "StackExchange"
} |
Q:
Syntax error uploading a .sql file in the Command Line
In the Command Line I created a database with:
create database mysql;
but when i try to upload a database file with the command:
mysql -u root -p database < dbdump.sql;
i receive a syntax error and i don't understand where i'm wrong
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'mysql
-u root -p database < dbdump.sql' at line 1
A:
confirm you're running the command from a shell and not from mysql.
I recall needing to be in mysql.exe directory when running such commands
remove the spaces around <. Ie, write mysql -u root -p database<dbdump.sql
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript: Swipe for Action Pattern Implementation
I have implemented the Swipe for Action Android pattern in my mobile web application (PhoneGap) using JavaScript & CSS animations/transitions.
However, there's one thing that's still eluding me.
I wish, that once the action menu is displayed fully and the user clicks anywhere outside of the action menu (labelled 3 in the figure), the menu should retract and the original item displayed (labelled 1 in the figure).
In a desktop application, one could "capture focus" and perform the transition back to (1) in lostfocus.
What is the JS equivalent of lostfocus event. I see an onfocus and onblur event, but from what I read it's really meant for things that need focus; like input, textarea, etc.
How else could I catch that event I'm interested in, other than putting some code in the touchend of every other element in the page and forcing the retraction of open actions explicitly?
A:
I think you gave the answer yourself. focus and blur are the events to be used for this and they are not exclusively meant for input elements, as you can see here [1].
I'm even trigger the focus event manually in a layer use case: A layer opens and I want to capture the keypress of ESC to close the layer. For this I need to set the focus on the layer as my event handler would not fire otherwise.
To capture the click outside you just need to register for pointerUp or click events on an element that spans the whole screen (it must really cover the whole screen like the body element). Because of the event bubbling the handler will fire as long as nothing else captured and cancelled it.
[1] https://dvcs.w3.org/hg/dom3events/raw-file/tip/html/DOM3-Events.html#event-type-blur
| {
"pile_set_name": "StackExchange"
} |
Q:
Orchard CMS - Extending Users with Fields - exposing values in Blog Post
I'd like to extend the users content definition to include a short bio and picture that can be viewed on every blog post of an existing blog. I'm unsure of what the best method to do this is.
I have tried extending the User content type with those fields, but I can't seem to see them in the Model using the shape tracing tool on the front end.
Is there a way to pass through fields on the User shape in a blog post? If so, what is the best way to do it?
A:
I also have done this a lot, and always include some custom functionality to achieve this.
There is a way to do this OOTB, but it's not the best IMO. You always have the 'Owner' property on the CommonPart of any content item, so in your blogpost view you can do this:
@{
var owner = Model.ContentItem.CommonPart.Owner;
}
<!-- This automatically builds anything that is attached to the user, except for what's in the UserPart (email, username, ..) -->
<h4>@owner.UserName</h4>
@Display(BuildDisplay((IUser) owner))
<!-- Or, with specific properties: -->
<h1>@T("Author:")</h1>
<h4>@owner.UserName</h4>
<label>@T("Biography")</label>
<p>
@Html.Raw(owner.BodyPart.Text)
</p>
<!-- <owner content item>.<Part with the image field>.<Name of the image field>.FirstMediaUrl (assuming you use MediaLibraryPickerField) -->
<img src="@owner.User.Image.FirstMediaUrl" />
What I often do though is creating a custom driver for this, so you can make use of placement.info and follow the orchard's best practices:
CommonPartDriver:
public class CommonPartDriver : ContentPartDriver<CommonPart> {
protected override DriverResult Display(CommonPart part, string displayType, dynamic shapeHelper) {
return ContentShape("Parts_Common_Owner", () => {
if (part.Owner == null)
return null;
var ownerShape = _contentManager.BuildDisplay(part.Owner);
return shapeHelper.Parts_Common_Owner(Owner: part.Owner, OwnerShape: ownerShape);
});
}
}
Views/Parts.Common.Owner.cshtml:
<h1>@T("Author")</h1>
<h3>@Model.Owner.UserName</h3>
@Display(Model.OwnerShape)
Placement.info:
<Placement>
<!-- Place in aside second zone -->
<Place Parts_Common_Owner="/AsideSecond:before" />
</Placement>
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot get values from GraphRequest Facebook
I'm using Facebook SDK 4.16.1 by using Profile I could get first name, last name, name and id my code is like this
public class LoginActivity extends Activity {
String id, fname, lname, email, name, gender, locale, verified;
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginactivity);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList(Constants.FACEBOOK_PERMISSIONS));
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
FB_TOKEN=loginResult.getAccessToken().getToken();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON:", object.toString());
try {
email = object.getString("email");
gender = object.getString("gender");
locale = object.optString("locale");
verified = object.optString("verified");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,last_name,email,gender,verified,locale");
request.setParameters(parameters);
request.executeAsync();
id = profile.getId();
fname = profile.getFirstName();
lname = profile.getLastName();
name = profile.getName();
nextActivity(profile);
Toast.makeText(getApplicationContext(), "Logging in...", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException e) {
}
};
loginButton.registerCallback(callbackManager, callback);
}
}
My constants looks like this
public static final String[] FACEBOOK_PERMISSIONS = new String[] {
"public_profile",
"user_friends",
"email" };
I'm trying to get the email, gender, locale and if its already verified. How will I get the other information? Mine are always null expect for the items that is get by Profile
Update
I update my GraphRequest like this
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
response.getError();
Log.e("JSON-RESULT:", object.toString());
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(object.toString());
email = jsonObject.getString("email");
gender = jsonObject.getString("gender");
locale = jsonObject.getString("locale");
verified = jsonObject.getString("verified");
Log.e(TAG, email + " This is the email");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,birthday,first_name,last_name,email,gender,verified,locale");
request.setParameters(parameters);
request.executeAsync();
In my Logcat it shows that I set the email and the others correctly but it doesn't go inside GraphRequest when you put breakpoints, and because of this my global variable email is still null. Even if in Log.e("JSON:", object.toString()); and Log.e(TAG, email + " This is the email"); it shows I get and set the values. I'm wondering how can I get the values of Bundle?
A:
Try using below code to fetch other info.....
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// Log.d("Login", "onSuccess");
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
email = me.optString("email");
String id = me.optString("id");
String email=me.optString("email");
String name= me.optString("name");
String gender= me.optString("gender");
String verified= me.optBoolean("is_verified") + "";
}
}
}).executeAsync();
}
@Override
public void onCancel () {
// Log.d("Login", "onCancel");
}
@Override
public void onError (FacebookException e){
// Log.d("Login", "onError " + e);
}
};
| {
"pile_set_name": "StackExchange"
} |
Q:
Click Every Word that ends with ".log.gz" in Any Language Compatible with Google Chrome
I have looked up the answer to this already and cannot do this with the programming languages I know, so I'd like the code for this and an explanation as to how it works so I can use this in future instances.
I have to download 300+ .log.gz files from a single page and would prefer not to manually click every single one. They all share the ending of .log.gz and begin with either "2014" or "2015". Is there a fairly simple code that I could execute inside Google Chrome that would allow me to click every single one of these (with a minor delay between each click) without having any manual support? I run Mac OS X Yosemite, if that helps.
EDIT:
The areas, in HTML, appear like this:
<tr class="downloadable">
<td><img src="Images/File.png" alt="File"></td>
<td>2014-09-24-1.log.gz</td>
<td>32.67 KB</td>
<td>September 25, 2014 at 5:00:08 AM GMT+1</td>
</tr>
Where I want to click:
<td>2014-09-24-1.log.gz</td>
A:
@BigDave's right on the money. Look for an extension that allows you to click-drag an area and open all the links inside, Like LinkClump. I have found that some of these programs can really cause the browser to lag, but that's expected when trying to open up so many links all at once.
Sounds like you're a micro-tasker/mechanical-turk worker?
Another idea is a macro-mouse program, if you can successfully assume that all the links are in a position that can be automatically clicked.
Yet another idea is to get ahold of a "visual programming language", ie, the bot programs that are typically used to cheat on video games, and clue the program to click on links based on their appearance.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert a Persian date into a Gregorian date?
I use the function below to convert Gregorian dates to Persian dates, but I've been unable to write a function to do the reverse conversion. I want a function that converts a Persian date (a string like "1390/07/18 12:00:00") into a Georgian date.
public static string GetPdate(DateTime _EnDate)
{
PersianCalendar pcalendar = new PersianCalendar();
string Pdate = pcalendar.GetYear(_EnDate).ToString("0000") + "/" +
pcalendar.GetMonth(_EnDate).ToString("00") + "/" +
pcalendar.GetDayOfMonth(_EnDate).ToString("00") + " " +
pcalendar.GetHour(_EnDate).ToString("00") + ":" +
pcalendar.GetMinute(_EnDate).ToString("00") + ":" +
pcalendar.GetSecond(_EnDate).ToString("00");
return Pdate;
}
A:
DateTime is always in the Gregorian calendar, effectively. Even if you create an instance specifying a dfferent calendar, the values returned by the Day, Month, Year etc properties are in the Gregorian calendar.
As an example, take the start of the Islamic calendar:
using System;
using System.Globalization;
class Test
{
static void Main()
{
DateTime epoch = new DateTime(1, 1, 1, new HijriCalendar());
Console.WriteLine(epoch.Year); // 622
Console.WriteLine(epoch.Month); // 7
Console.WriteLine(epoch.Day); // 18
}
}
It's not clear how you're creating the input to this method, or whether you should really be converting it to a string format. (Or why you're not using the built-in string formatters.)
It could be that you can just use:
public static string FormatDateTimeAsGregorian(DateTime input)
{
return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
CultureInfo.InvariantCulture);
}
That will work for any DateTime which has been created appropriately - but we don't know what you've done before this.
Sample:
using System;
using System.Globalization;
class Test
{
static void Main()
{
DateTime epoch = new DateTime(1, 1, 1, new PersianCalendar());
// Prints 0622/03/21 00:00:00
Console.WriteLine(FormatDateTimeAsGregorian(epoch));
}
public static string FormatDateTimeAsGregorian(DateTime input)
{
return input.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss",
CultureInfo.InvariantCulture);
}
}
Now if you're not specifying the calendar when you create the DateTime, then you're not really creating a Persian date at all.
If you want dates that keep track of their calendar system, you can use my Noda Time project, which now supports the Persian calendar:
// In Noda Time 2.0 you'd just use CalendarSystem.Persian
var persianDate = new LocalDate(1390, 7, 18, CalendarSystem.GetPersianCalendar());
var gregorianDate = persianDate.WithCalendar(CalendarSystem.Iso);
A:
Thanks guys,I used below code and my problem solved:
public static DateTime GetEdate(string _Fdate)
{
DateTime fdate = Convert.ToDateTime(_Fdate);
GregorianCalendar gcalendar = new GregorianCalendar();
DateTime eDate = pcalendar.ToDateTime(
gcalendar.GetYear(fdate),
gcalendar.GetMonth(fdate),
gcalendar.GetDayOfMonth(fdate),
gcalendar.GetHour(fdate),
gcalendar.GetMinute(fdate),
gcalendar.GetSecond(fdate), 0);
return eDate;
}
A:
Use this code to convert Persian to Gregorian date and vice versa.
public static class PersainDate
{
public static DateTime ConvertToGregorian(this DateTime obj)
{
DateTime dt = new DateTime(obj.Year, obj.Month, obj.Day, new PersianCalendar());
return dt;
}
public static DateTime ConvertToPersian(this DateTime obj)
{
var persian = new PersianCalendar();
var year = persian.GetYear(obj);
var month = persian.GetMonth(obj);
var day = persian.GetDayOfMonth(obj);
DateTime persiandate = new DateTime(year, month, day);
return persianDate;
}
}
Use the code this way
var time = DateTime.Now;
var persianDate = time.ConverToPersian();
var gregorianDate = persianDate.ConverToGregorian();
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create front end AJAX handler which validates and adds comment to content?
I am attempting to create a "Leave Comment" form which is loaded by AJAX on demand and then shown using a jQuery popup. There are three motivations for this:
Less clutter on page.
Reduced automated spam.
Faster page load time (with caching enabled the page load time goes from 400ms to 120ms when the comment form is not included in the article template).
Here is what I have currently:
I have created the following template which is called ajax/blog-comment-form:
{exp:comment:form channel="blog" entry_id="{segment_3}"}
{if logged_out}
<label for="name">Name:</label> <input type="text" name="name" value="{name}" size="70" /><br />
<label for="email">Email:</label> <input type="text" name="email" value="{email}" size="70" /><br />
<label for="url">URL:</label> <input type="text" name="url" value="{url}" size="70" /><br />
{/if}
<label class="outline" for="comment">Comment:</label>
<textarea name="comment" cols="70" rows="7">{comment}</textarea>
<div class="comment-note">Note: HTML tags are not supported.</div>
{if captcha}
<div class="captcha">
<label for="captcha">Please enter the word you see in the image below:</label>
{captcha} <input id="captcha" type="text" name="captcha" value="{captcha_word}" maxlength="20" />
</div>
{/if}
<div class="button-strip">
<input class="ui-pink-button" type="submit" name="submit" value="Submit" />
</div>
</div>
{/exp:comment:form}
I am currently using the following JavaScript to submit the form via AJAX. This is almost working except there is no way to display error messages when inputs are entered incorrectly.
form.find('input[name="submit"]').click(function() {
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
// ???
},
failed: function(data) {
// ???
// this never seems to actually occur
}
});
return false;
});
A:
TL;DR: You're binding a callback to the wrong $.ajax option, but that isn't enough to fix this: I would use the Ajax Babble addon and get on with your day, as this problem turns out to be more complex than it looks. While you could do client side validation as Anna suggests, there are all sorts of other error conditions not related to request content that you can't validate client side, such as requiring an IP, minimum time between comments etc.
Anyway if $35 is too much for your budget then by all means read on...
The long answer...
Sorry this is so long, but I had a little time on my hands...
The first reason that your failed callback is never called is failed is not the name of the $.ajax option that you want, you want fail (jQuery 1.8+) or error (pre jQ 1.8).
However, even if you change that, the callback still won't fire because of the fact that the ajax request is returning successfully (ie an HTML response with a 200 HTTP status code), it's just that the response is an EE error page, rather than an error code. jQuery doesn't understand the content of that page, so unless it returns HTTP error code such as a 403 or 500, which it doesn't that code will never run.
Before we get to the non-addon route to solving this, a few jQuery/JS notes:
You should bind to the forms submit event, rather than a click handler on the submit button, as forms can be submitted without clicking (keyUp/JS triggered submit etc).
Use event.preventDefault() instead of return false, as doing the latter from a jQuery event handler is the equivalent of calling both event.preventDefault() and event.stopPropagation(), the latter of which which stops the event from bubbling.
You may want to do this, but if so do it explicitly to avoid debugging headaches with delegated events:
$('form').on('submit', function(e){
//the first argument passed to the event handler is the jQ wrapped event object
e.preventDefault();
//handle event here
}).addClss
Consider using jQuery deferreds instead of passing callbacks as options to $.ajax. It makes your code easier to read and you can register callbacks where it makes sense rather than where $.ajax wants you too. You can even register callbacks on requests that have already returned (in which case they execute immediately):
$('form').on('submit', function(e){
var req = $.ajax({...}); //returns a jQ deferred object
e.preventDefault();
...
req.done(function(){
//handle success
alert('yay!');
})
.fail(function(){
//handle error
alert('boo!');
})
.always(function(){
//fires when request done whether successful or not
alert('finished!');
});
});
Enough already, how do I roll my own Ajax comment submission?
Okay so, if you really want to go down the route of rolling your own for this one, you're going to need to parse the response in some way (such as by looking for an id on the body element of the message template) and then extract the message:
In your system message template:
<body class="system-msg">
<div class="system-msg-content">
{content}
</div>
</body>
In your jQuery:
//not tested, may need tweaking
req.done(function(data, status){
var $data = $(data),
msg = $('<p class="msg"/>'),
msgContent;
if ($data.find('body').hasClass('system-message')){
//handle error message
msgContent = $data.find('.system-msg-content').html();
$msg.html(msgContent);
$form.prepend($msg);
}
else {
//do normal success stuff here
}
})
You could even use the Custom System Messages addon and Mo'Variables to use a regular template for your error and then detect an ajax request and return a differently formatted response (or even an error code, in which case you can use fail())for consumption by your jQuery.
But to be honest, I wouldn't do any of that unless you don't really value your time or you enjoy the challenge, instead I'd stump up $35 for Ajax Babble and go home early instead.
| {
"pile_set_name": "StackExchange"
} |
Q:
Create alias using bash one liner
I need to create alias for my long command, normally I would use
alias myLongCommand="my long command"
but I need to define in an online system configuration where I can only use bash command, I tried various combinations including:
bash -c 'alias myLongCommand="my long command"'
but unfortunately with no success, alias does not get defined.
To test success I use
bash -c myLongCommand
A:
Short answer: Use an exported function instead
# define a function
myLongCommand() { my long command; }
# export that function to the environment
export -f myLongCommand
# thereafter, that function is available in subprocesses
bash -c 'myLongCommand'
...or, to compress the actual creation into a one-liner:
myLongCommand() { my long command; }; export -f myLongCommand
Note that the definition and export needs to be done in a bash shell that is itself a parent process of the shell in which you intend the function to be used. If you use bash -c 'myLongCommand() { my long command; }; export -f myLongCommand', then the environment variable with the exported function lives only as long as that bash -c instance does -- hence, it's entirely unavailable in any subsequent command.
If you wanted this to be available for all bash shells in your login session, you could put the definition and export in ~/.bash_profile (and log out and back in), if your system is behaving per typical defaults with respect to dotfile initialization.
Longer answer: Why did the original attempt fail?
Multiple reasons:
Aliases are part of the state of an individual shell process -- there isn't a shared registry. Thus, bash -c 'alias foo="bar"' sets up an alias only for that single bash instance created by the bash -c command, and that alias is terminated when that command exits.
Noninteractive shells, such as those created with bash -c, don't inherit aliases from their parent processes, or read dotfiles (by default), so they start out with their alias table empty, even if an alias is defined in the (separate) shell that's invoking them.
Noninteractive shells, such as those created with bash -c, have alias evaluation turned off by default, as this is intended to be an interactive-use feature.
Longer answer: Why not an alias?
Aliases are intended as a facility for interactive use. Thus, they're not by default available inside noninteractive shells at all. To enable alias expansion in a noninteractive instance of bash, one needs to run:
shopt -s expand_aliases
The other issue is actually getting that alias defined at all. Noninteractive shells don't run dotfiles by default (the name of a dotfile to run in a noninteractive shell can be placed in the ENV or BASH_ENV environment variable to override this), so they won't have aliases defined in ~/.bashrc present.
Longer answer: ...so, how could you use an alias?
# create a .env file, taking care not to fail badly if shell is not bash
# note that making noninteractive shells emit content on stderr will break some software
# ...so redirecting errors is entirely essential here, and ||: is necessary to not break
# ...any noninteractive shell (like dash or ash invocations) that doesn't support shopt
# ...when that shell is invoked with the -e argument.
cat >~/.env <<'EOF'
shopt -s expand_aliases 2>/dev/null ||: "fail gracefully w/o shopt"
alias myLongCommand="my long command" 2>/dev/null ||: "fail gracefully w/o aliases"
EOF
# point to it from your .bash_profile
cat >>~/.bash_profile <<'EOF'
export ENV=$HOME/.env
[[ -e $ENV ]] && source "$ENV"
EOF
# ...and update the already-running shell:
export ENV=$HOME/.env
source "$ENV"
...to do the above in one line:
printf '%s\n' 'shopt -s expand_aliases 2>/dev/null ||:' 'alias myLongCommand="my long command" 2>/dev/null ||:' >~/.env; printf '%s\n' 'export ENV=$HOME/.env' '[[ -e $ENV ]] && source "$ENV"' >>~/.bash_profile
| {
"pile_set_name": "StackExchange"
} |
Q:
Break long titles (containing file paths) with BibLaTeX
I am currently trying to get linebreaks inside long bibliography entry titles which have no whitespace to break at.
Let us assume that we have the following MWE with its minimal bibliography entry (this is just an example, the real entries would have more information of course) which should be displayed correctly:
\documentclass{scrartcl}
\usepackage[%
backend=biber,
style=alphabetic,
]{biblatex}
\addbibresource{\jobname.bib}
\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@software{key,
title = {Software repository: /usr/share/php/PHP/CodeSniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php},
author = {Sherwood, Greg},
}
\end{filecontents}
\begin{document}
\cite{key}
\printbibliography
\end{document}
Currently the whole bibliography entry takes one line in the output only and is not shown completely. I think the best way to break the entry would be at one of the slashes.
The .bib file itself is being created using Zotero and might be overwritten. I could edit the title manually in Zotero (which is not portable across multiple documents) or modify the exported file (which might be overwritten again later on), but these are not the best options in my opinion.
Is there anything I can do about this which does not require manual modifications of the .bib file?
A:
I'd define a new command based on url.sty's \url for file paths.
\documentclass{scrartcl}
\usepackage[%
backend=biber,
style=alphabetic,
]{biblatex}
\usepackage{url}
\newcommand*{\filepath}{}
\DeclareUrlCommand\filepath{\urlstyle{same}}
\begin{filecontents}{\jobname.bib}
@software{key,
title = {Software repository: \filepath{/usr/share/php/PHP/CodeSniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php}},
author = {Sherwood, Greg},
}
\end{filecontents}
\addbibresource{\jobname.bib}
\begin{document}
\cite{key}
\printbibliography
\end{document}
I am aware that this does not meet the "I don't want to modify the .bib file" desideratum, but I think in this case this is the most sensible thing to do. LaTeX just needs some markup to know what to do with the file path. You wouldn't expect LaTeX to hyphenate French phrases according to French rules in an otherwise English document unless you explicitly mark up the French phrase.
If you insist on a solution without changes to the .bib file you can run the following with LuaLaTeX. It replaces every occurrence of / with a breakable slash.
% !TeX program = LuaLaTeX
\documentclass{scrartcl}
\usepackage[%
backend=biber,
style=alphabetic,
]{biblatex}
\newcommand{\breakslash}{/\penalty\exhyphenpenalty\hspace{0pt}}
\usepackage{luacode}
\begin{luacode}
function replaceslash (s)
s = string.gsub (s, "/", "\\breakslash " )
tex.sprint (s)
end
\end{luacode}
\newcommand{\replaceslash}[1]{\directlua{replaceslash(\luastringN{#1})}}
\DeclareFieldFormat{titlecase}{\replaceslash{#1}}
\begin{filecontents}{\jobname.bib}
@software{key,
title = {Software repository: /usr/share/php/PHP/CodeSniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php},
author = {Sherwood, Greg},
}
\end{filecontents}
\addbibresource{\jobname.bib}
\begin{document}
\cite{key}
\printbibliography
\end{document}
Or much, much more fragile, some code that assumes that everything starting with / up to the next space is a file path.
% !TeX program = LuaLaTeX
\documentclass{scrartcl}
\usepackage[%
backend=biber,
style=alphabetic,
]{biblatex}
\usepackage{url}
\newcommand*{\filepath}{}
\DeclareUrlCommand\filepath{\urlstyle{same}}
\usepackage{luacode}
\begin{luacode}
function replaceslash (s)
s = string.gsub (s, "(/[^%s]*)", "\\filepath{%1}" )
tex.sprint (s)
end
\end{luacode}
\newcommand{\replaceslash}[1]{\directlua{replaceslash(\luastringN{#1})}}
\DeclareFieldFormat{titlecase}{\replaceslash{#1}}
\begin{filecontents}{\jobname.bib}
@software{key,
title = {Software repository: /usr/share/php/PHP/CodeSniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php},
author = {Sherwood, Greg},
}
\end{filecontents}
\addbibresource{\jobname.bib}
\begin{document}
\cite{key}
\printbibliography
\end{document}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Gremlin (AWS Neptune), how can I get all paths of length n from a starting node traversing edges with specific criteria?
Starting with node 1, I want to return all the paths (edges and vertices, with id/label/properties) within n hops following any outbound edges, or following inbound edges with a property predicate (p > 50).
Ideally the paths shouldn't contain any cycles, so a path shouldn't contain the same node twice.
The property p is not present on every edge.
g.addV().property(id, 1).as('1').
addV().property(id, 2).as('2').
addV().property(id, 3).as('3').
addV().property(id, 4).as('4').
addV().property(id, 5).as('5').
addV().property(id, 6).as('6').
addV().property(id, 7).as('7').
addV().property(id, 8).as('8').
addE('pointsAt').from('1').to('2').
addE('pointsAt').from('3').to('1').
addE('pointsAt').from('4').to('1').property('p', 10).
addE('pointsAt').from('5').to('1').property('p', 100).
addE('pointsAt').from('2').to('6').
addE('pointsAt').from('7').to('2').
addE('pointsAt').from('8').to('2').property('p', 100).
iterate()
Assuming we start at Vertex 1 the paths would look like:
1>2
1>2>6
1>2>8
1>5
1-2 is included because it's outbound
1-3 is excluded because it is inbound to 1 and doesn't have p
1-4 is excluded because it is inbound and (p > 50) is false
1-5 is included because it is inbound and (p > 50) is true
2-6 is included because it's outbound
2-7 is excluded because it is inbound to 2 and doesn't have p
2-8 is included because it is inbound to 2 and p > 50
I've experimented with many different approaches and I can't seem to get anything close to what I am looking for.
A:
I believe this is what you're looking for:
g.V(1).
repeat(
union(
outE(),inE().has('p',gt(50))
).
otherV().simplePath()).
emit().
times(2).
path().
by(valueMap().with(WithOptions.tokens))
The repeat() and times() steps dictate that this is a recursive traversal going to a depth of 2. The union() step and containing arguments follow your requirements to include all outgoing edges and only incoming edges with a p property greater than 50. The emit() step forces the repeat() step to stream all paths as they are found. If you didn't include this, you would only get the paths found of length 2 (declared in the times() step).
To wrap this up, we use path() and by() to output the paths found and all of the ids, labels, and properties for each vertex and edge in the path.
The output of this from the graph that you provided looks like this:
==>[[id:1,label:vertex],[id:0,label:pointsAt],[id:2,label:vertex]]
==>[[id:1,label:vertex],[id:3,label:pointsAt,p:100],[id:5,label:vertex]]
==>[[id:1,label:vertex],[id:0,label:pointsAt],[id:2,label:vertex],[id:4,label:pointsAt],[id:6,label:vertex]]
==>[[id:1,label:vertex],[id:0,label:pointsAt],[id:2,label:vertex],[id:6,label:pointsAt,p:100],[id:8,label:vertex]]
| {
"pile_set_name": "StackExchange"
} |
Q:
HotTowel Durandal Inject different views based on the user
In the shell.html for HotTowel template we have:
<!--ko compose: {model: router.activeItem,
afterCompose: router.afterCompose,
transition: 'entrance'} -->
<!--/ko-->
which will automatically insert the proper view by convention. I am trying to inject different views based on the user's role in a HotTowel/Durandal App. For example,
I have two Views,
productEditor_Admin.html
productEditor_Superviser.html
(instead of these two views, I used to have only productEditor.html, by convention everything worked)
and only a single ViewModel:
productEditor.js
Now, I want to have a function in productEditor.js that will let me decide which view to insert based on user's role. I see in the Composition documentation, we can do function strategy(settings) : promise but I am not sure what's the best way to accomplish this in the HotTowel template. Anyone have already tried and got an answer for that?
A:
It's possible to return a 'viewUrl' property in the view model, so hopefully something like the following will crack the door open ;-).
define(function () {
viewUrl = function () {
var role = 'role2'; //Hardcoded for demo
var roleViewMap = {
'default': 'samples/viewComposition/dFiddle/index.html',
role1: 'samples/viewComposition/dFiddle/role1.html',
role2: 'samples/viewComposition/dFiddle/role2.html'
};
return roleViewMap[role];
}
return {
viewUrl: viewUrl(),
propertyOne: 'This is a databound property from the root context.',
propertyTwo: 'This property demonstrates that binding contexts flow through composed views.'
};
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Preventing blender name indexing
I'm using a python script to import and export wavefront obj files in Blender. The problem is that Blender adds an index to an object's name if an object with the same name was already added. For example myObject becomes myObject.001 if there was already an object called myObject added in the past (even if said object was removed). When I export the object as .obj the names are no longer the same as before.
How do I reset that "name-counter"?
A:
Each item in blender must have a unique name within the list of items it belongs to (each name is a dictionary key) and will make a name unique by appending a numeric suffix based on the other items within the file, note that it is based on the file - not the scene, as a blend file can contain multiple scenes. Objects that have been deleted are not considered in this process, while other items like materials and mesh data remain in the lists until the file is closed.
The obj importer first creates the mesh datablock and then creates an object using the same name as the mesh data - this leads to the new objects always having a numeric suffix larger than previous objects.
If you are importing multiple objects using a python script you can rename the object after you import it.
bpy.ops.import_scene.obj(filepath='Object1.obj')
bpy.context.selected_objects[0].name = 'Object'
bpy.context.selected_objects[0].data.name = 'Object'
In this scenario any existing object with the name "Object" will get renamed to have a suffix.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I spawn a synchronous process in VB6 and retrieve its return value?
Is it possible to spawn a synchronous process in VB6 (i.e. calling an external .exe), wait for it to terminate, and grab the return value?
We have legacy code (in VB6 obviously) that we need to call a .NET application to perform some complicated tasks, and based on the .NET app's return value, either proceed or fail. Is there a better way of doing such a thing?
A:
Your first option should probably be to expose an interface to expose the .NET interfaces to COM and use that (it is much cleaner), but if for some reason you have to do it through a spawned process use this VB6 code.
Private Type STARTUPINFO
cb As Long
lpReserved As String
lpDesktop As String
lpTitle As String
dwX As Long
dwY As Long
dwXSize As Long
dwYSize As Long
dwXCountChars As Long
dwYCountChars As Long
dwFillAttribute As Long
dwFlags As Long
wShowWindow As Integer
cbReserved2 As Integer
lpReserved2 As Long
hStdInput As Long
hStdOutput As Long
hStdError As Long
End Type
Private Type PROCESS_INFORMATION
hProcess As Long
hThread As Long
dwProcessID As Long
dwThreadID As Long
End Type
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateProcessA Lib "kernel32" (ByVal lpApplicationName As Long, ByVal lpCommandLine As String, ByVal lpProcessAttributes As Long, ByVal lpThreadAttributes As Long, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, ByVal lpEnvironment As Long, ByVal lpCurrentDirectory As Long, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long
Private Const NORMAL_PRIORITY_CLASS = &H20&
Private Const INFINITE = -1&
Private Const SW_HIDE = 0
Private Const SW_SHOWMINNOACTIVE = 7
Public Function ExecCmd(cmdline As String, workdir As String) As Integer
Dim proc As PROCESS_INFORMATION
Dim start As STARTUPINFO
Dim ret as Long
ChDrive Left(workdir, 1) & ":"
ChDir workdir
start.cb = Len(start)
start.wShowWindow = SW_SHOWMINNOACTIVE
Call CreateProcessA(0&, cmdline, 0&, 0&, 1&, NORMAL_PRIORITY_CLASS, 0&, 0&, start, proc)
Call WaitForSingleObject(proc.hProcess, INFINITE)
Call GetExitCodeProcess(proc.hProcess, ret)
Call CloseHandle(proc.hThread)
Call CloseHandle(proc.hProcess)
ExecCmd=ret
End Function
| {
"pile_set_name": "StackExchange"
} |
Q:
Datagrid Binding Using MVVM WPF
I'm facing an issue in datagrid binding using mvvm on two different places. Headers of my datagrid (xaml) is:
<DataGrid Grid.Row="0" Grid.Column="0" AlternationCount="2" Background="White" RowHeight="28" HorizontalGridLinesBrush="Lavender" VerticalGridLinesBrush="Lavender"
VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch" IsSynchronizedWithCurrentItem="True"
ScrollViewer.CanContentScroll="True" Name="MainGrid" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Visible"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="False" CanUserAddRows="False"
CanUserDeleteRows="False" CanUserResizeRows="True" ItemsSource="{Binding Path=Configurations, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
which clealy says
ItemsSource="{Binding Path=Configurations, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
In my viewmodel:
public ObservableCollection<ViewerConfiguration> Configurations
{
get { return m_tasks; }
set { m_tasks = value; OnPropertyChanged("Configurations"); }
}
The data that in the list is shown properly on the view but the problem is with the insert and delete (even it updates successfully).
I have a function which inserts an item in the Configuration object
private void Refresh()
{
List<ViewerConfiguration> newlyAddedFiles = GetConfigurations();
foreach (ViewerConfiguration config in newlyAddedFiles)
{
Configurations.Add(config);
}
}
and removes like:
Configurations.Remove(configuration);
The problem is really with the insert and delete. On debugging there is no exception and it successfully deletes from collection too but UI doesn't get a notification. Any guesses why is this behavior?
Additionally:
I have an event trigger just under the datagrid:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding RenderPdf}" CommandParameter="{Binding SelectedItem, ElementName=MainGrid}"></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
and I'm calling Refresh function from the constructor of ViewModel just to see if it works or not.
A:
Finally I solved the issue i was having. There were basically two problems. In the getter of my Configurations, i was return a new observable collection after sorting and filtering the previous one.
The second main problem:
'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread'
That was my best guess and i changed my refresh function to:
private void Refresh()
{
try
{
List<ViewerConfiguration> newlyAddedFiles = GetConfigurations();
//should not update on other thread than on main thread
App.Current.Dispatcher.BeginInvoke((ThreadStart)delegate()
{
foreach (ViewerConfiguration config in newlyAddedFiles)
{
Configurations.Add(config);
}
});
}
catch (Exception ex)
{
}
}
Now, its working.
Thanks
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do ceramic insulators have a stacked disc structure?
I've seen these stacked-disc structures on high voltage power lines everywhere. I could not find any information regarding this particular shape, though.
From what I've noticed, high voltage ceramic insulators only insulate conductors end-to-end (not inside to outside, like traditional plastic insulators). I can only assume the shape makes it difficult for an electric arc to travel along the ceramic material, as opposed to, say, along a solid cylindrical piece.
Why exactly are ceramic insulators shaped like that? Is it to reduce cost? Thermal concerns (from possible electric arcs)?
A:
Electricity can more easily travel across a surface of an insulator. If the surface is made longer it makes the surface path longer and thus is able to withstand higher voltages before breaking down.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I name these classes under the BEM methodology?
Image below is the output of my code
Are these names correct under BEM methodology?
<div class="container">
<div class="container__button-row--1">
<div class="button-row__button--first"></div>
<div class="button-row__button"></div>
<div class="button-row__button"></div>
...
<div class="button-row__button--last"></div>
</div>
<div class="container__button-row--2">
...
</div>
</div>
A:
Given the sample code in your question I'd suggest the following. But I would also point out that container is a bad name for a component/Block since it really general and does not indicate the purpose of the Block.
For modifiers you should use both the element and the modifier in the class attribute e.g. block__element block__element--modifier
<div class="container">
<div class="container__button-row container__button-row--1">
<div class="container__button container__button--first"></div>
<div class="container__button"></div>
<div class="container__button"></div>
...
<div class="container__button container__button--last"></div>
</div>
<div class="container__button-row container__button-row--2">
...
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Bootstrap 4 - keep columns with static width and no wrapping
I am trying to get this layout working: Columns keep constant width when I resize the browser and they dont wrap - instead a horizontal scroll bar appears as soon as it reaches the min width. My code:
<div class="card card-outline-primary" style="min-width:500px">
<div class="card-block container-fixed">
<form class="row">
<div class="col-4" style="border:solid;border-color:red;border-width:5px;min-width:250px">
<label for="visualTheme" class="control-label">1234</label>
<div>
<input class="form-control" style="height:30px;width:200px" id="visualTheme" />
</div>
</div>
<div class="col-4" style="border:solid;border-color:blue;border-width:5px;min-width:250px">
<label class="control-label">5678</label>
<div>
<input class="form-control" style="height:30px;width:200px" id="startingScreen" />
</div>
</div>
<div class="col-4" style="border:solid;border-color:green;border-width:5px;min-width:250px">
</div>
</form>
</div>
And Fiddle:
Fiddle
If I use min width for columns they wrap.
Thanks for the help.
A:
Use the flex-nowrap class on the row..
<form class="row flex-nowrap"></form>
| {
"pile_set_name": "StackExchange"
} |
Q:
Magento event paid status
Does anyone know how to implement a custom "module" that is triggered when an order is paid or complete?
And how am I able to call the order data from that observer?
I am also working with the "Serial Codes" plugin, and I want to send
an email to the person who bought this product, containing the serial
code.
Is there anybody who is able to help me out?
A:
You can write an observer for the sales_order_save_before event. In the observer method you are able to get the order by $observer->getEvent()->getOrder(). Then you can check for the order status/state and add your code when the order is completed. This is the safest way, with the small downside, that the Observer function will always be triggered when the order is saved. Example Code:
public function onCompleteOrder(Varien_Event_Observer $observer)
{
/** @var $order Mage_Sales_Model_Order */
$order = $observer->getEvent()->getOrder();
if ($order->getState() == Mage_Sales_Model_Order::STATE_COMPLETE) {
// do something
}
return $this;
}
By the way: A Magento order is usually becoming completed when
An invoice has been created AND
a shipment has been created
| {
"pile_set_name": "StackExchange"
} |
Q:
Use Addon domain within login name for FTP account in cPanel
Let's say I have a cPanel (version 11.30.6 (build 3), cPanel Pro 1.0 (RC1)) shared hosting account for myDomain.com.
I also have several other "Addon" domain names on this account, each with their own document root.
Under the cPanel FTP Accounts page, it only allows me to do this...
Server: ftp.myDomain.com
Login: [email protected]
However, I want to setup an FTP location at one of my "Addon" domains so that it looks like this...
Server: ftp.myAddonDomain.net
Login: [email protected]
I'm not seeing if it's even possible, but hoping it is, and somebody here would be able to explain how.
In other words, cPanel allows me to create an email account at literally any of my Addon domains or sub-domains. I'm wondering if I can create FTP accounts in the same fashion... but it's looks like I cannot.
A:
I discussed this with Tech Support at my hosting provider.
It's not possible to have unique FTP accounts without using the main domain name within the server & login names.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I create an RSS feed from Salesforce activity?
I'd like to create an RSS feed when certain Accounts are created and updated. The end goal is exposing certain data elements on an external directory page in Wordpress. Wordpress has many RSS plugins - but so far the only info I can find on this is in this 2010 blog post: http://techsahre.blogspot.ca/2010/03/rss-feed-power-with-salesforce.html ? Any better / more native / simpler ways to do this?
A:
If you are exposing the feed to an external page (meaning it's public), the platform has support for generating atom feeds (similar to RSS).
See: http://developer.force.com/cookbook/recipe/adding-a-feed-to-your-force-com-site
| {
"pile_set_name": "StackExchange"
} |
Q:
Delete files from trash after x days
Is there any way to configure Ubuntu to permanently delete files from trash after a certain amount of time?
I don't get why that's not the default behavior in any major OS. I don't want to think about administrating my trash, but I don't want to accidentally delete something either. Am I the only one with that opinion?
A:
Use trash-cli
(click image to install or run sudo apt-get install trash-cli).
Run trash-empty 30 to remove all files from trash which are older than 30 days. (You can change this number as you like.)
To automate this, add a command to Startup Applications:
Please note: If you use older Ubuntu versions than 12.04, the command is empty-trash!
A:
If you're on GNOME, there's now a feature for that! Go to Privacy in your settings and look under Purge Trash & Temporary Files.
More at https://help.gnome.org/users/gnome-help/stable/privacy-purge.html.en.
A:
Try with Autotrash!
Autotrash is a simple Python script comes with Ubuntu 10.10 Maverick Meerkat which will purge files from your trash when they become older than a given days,purge older files to ensure a specific amount of disk space is free,etc.It uses the FreeDesktop.org Trash Info files included in the new GNOME system to find the correct files and the dates they where deleted.
Features:
Remove files that are older then a given number of days
(autotrash -d N,where N is the number of days)
Purge older files to ensure a specific amount of disk space is free
(autotrash --min-free=M,M is the amount of free space you want to ensure you have, in megabytes.)
Check for remaining disk space, and only delete if you are running out
(autotrash --max-free=M,M is the amount of free space left, in megabytes.)
Delete regex matching files first (see –delete-frist option)
For more info,execute this in terminal:
autotrash --help
AutoTrash is already in Ubuntu 10.10′s repository,it can be installed from Ubuntu Software Center.For Ubuntu 10.04 and 9.10 user,install this from PPA:
sudo add-apt-repository ppa:nilarimogard/webupd8
sudo apt-get update
sudo apt-get install autotrash
Info: http://www.logfish.net/pr/autotrash/
Source: http://ubuntuguide.net/automatically-delete-files-older-than-n-days-from-trash-using-autotrash/
For a different approach and a more comprehensive guide: http://helpdeskgeek.com/linux-tips/automatically-empty-the-trash-in-ubuntu/
| {
"pile_set_name": "StackExchange"
} |
Q:
select query in subquery giving Column is invalid in the select list because it is not contained error
I have following query which i want to get sum counts for my data
SELECT
TI.[text] as zone,
YEAR (ER.Inserted) as [Year],
SUM(CONVERT(INT,DRT.RDRT)) as RDRT,
SUM(CONVERT(INT,DRT.FACT)) as FACT ,
SUM(CONVERT(INT,DRT.ERU)) as ERU,
(
SELECT COUNT(ER1.ReportID)
FROM dbo.EW_Reports ER1
INNER JOIN dbo.EW_Report_InformationManagement ERI ON ER1.ReportID = ERI.ReportID
INNER JOIN EW_Report_Country ERC1 ON ER1.ReportID = ERC1.ReportID
INNER JOIN ApplicationDB.dbo.Country C1 ON ERC1.CountryID = C1.countryId
INNER JOIN ApplicationDB.dbo.Region R1 ON C1.regionId = R1.regionId
INNER JOIN ApplicationDB.dbo.Zone Z1 ON R1.zoneId = Z1.zoneId
WHERE ERI.EmergencyAppeal IS NOT NULL
AND (YEAR ( ER1.Inserted) = YEAR ( ER.Inserted))
AND Z1.zoneId = Z.zoneId
) as emergencyAppeals
FROM EW_Reports ER
INNER JOIN EW_DisasterResponseTools DRT ON ER.ReportID = DRT.ReportID
INNER JOIN EW_Report_Country ERC ON ER.ReportID = ERC.ReportID
INNER JOIN ApplicationDB.dbo.Country C ON ERC.CountryID = c.countryId
INNER JOIN ApplicationDB.dbo.Region R ON c.regionId = R.regionId
INNER JOIN ApplicationDB.dbo.Zone Z ON R.zoneId = Z.zoneId
INNER JOIN ApplicationDB.dbo.Translation T ON Z.translationId = T.translationId
INNER JOIN ApplicationDB.dbo.TranslationItem TI ON T.translationId = TI.translationId
INNER JOIN EW_lofDisasterTypes D ON ER.DisasterTypeID = D.TranslationID AND D.LanguageID = 1 AND TI.languageID = 1
WHERE (YEAR ( ER.Inserted) IN (2011,2012))
GROUP BY TI.[text], YEAR (ER.Inserted)
But its giving following error
Column 'ApplicationDB.dbo.Zone.zoneId' is invalid in the select list
because it is not contained in either an aggregate function or the
GROUP BY clause.
Please assist me how to resolve this error .
A:
there are too many ApplicationDB.dbo.Zone.zoneId records in your table already
simple add ApplicationDB.dbo.Zone.zoneId in group by then problem will solved
Select ....
.....
GROUP BY TI.[text], YEAR (ER.Inserted) ,ApplicationDB.dbo.Zone.zoneId
For your question why u need to add ApplicationDB.dbo.Zone.zoneId in my group as i am using that in ur subquery, this is because u perform a outer condition in your subquery
SELECT
----
(
SELECT
-----
INNER JOIN ApplicationDB.dbo.Zone Z1 ON R1.zoneId = Z1.zoneId
WHERE
----
AND Z1.zoneId = Z.zoneId
)
-----
INNER JOIN ApplicationDB.dbo.Zone Z ON R.zoneId = Z.zoneId
WHERE (YEAR ( ER.Inserted) IN (2011,2012))
------
note that you have a condition in different years
so your data flow may like this
ZoneID Years Record
1 2011 1000
1 2012 1000
same zone id contain different years, without proper grouping, sql got no way to group years column
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving $f\in\mathbb{C}(D)$ if and only if for every closed set $F\subseteq R^m$, $f^{-1}(F)$ is closed (relatively) in $D$.
I am confident in my first inclusion but I am quite lost in my second. Can I please have help?
$\def\x{{\mathbf x}}
\def\R{{\mathbb R}}
\def\C{{\mathbb C}}
\def\f{{\mathbf f}}$
Let $\f\colon D\to \R^m$, $D\subseteq\R^n$. Prove $\f\in\C(D)$ if and only if for every closed set $F\subseteq \R^m$, $\f^{-1}(F)$
is closed (relatively) in $D$.
$\textbf{Solution:}$
$(\rightarrow)$ Suppose $\f\in\C(D)$ and $F$ be any arbitrary closed set in $\R^m$. Our claim is that $\f^{-1}(E)$ is relatively closed in $D$. $F$ is a closed set in $\R^m$ if and only if $\R^m \setminus F$ is open set in $\R^n$. As $\f$ is continuous on $D$,
$$\f^{-1}(\R^m\setminus E) \text{ is open (relatively) in } D$$ $$\f^{-1}(\R^m \setminus E) = \f^{-1}(\R^m)\setminus \f^{-1}(E) = D\setminus \f^{-1}(E)$$ because $\f^{-1}(A\setminus B) = \f^{-1}(A)\setminus \f^{-1}(A) \setminus \f^{-1} (B)$ and $\f^{-1}(\R^n) = D$.
Then, $D\setminus \f^{-1}(E)$ is open (relatively) in $D$. Thus, $D\setminus (D\setminus \f^{-1}(E)) = \f^{-1}(E)$ is relatively closed in $D$. This is for all $E$ closed in $\R^n$.
$(\leftarrow)$ Conversely, suppose for every $F$ closed in $\R^m, \f^{-1}(F)$ is relatively closed in $D$. Our claim is that $\f$ is continuous, $\f \in \C(D)$, i.e. for every open set $E \subseteq \R^m, \f^{-1}(E)$ is relatively open in $D$. $E$ is any open set in $\R^m$ which is equivalent to saying $\R^m \setminus E$ is closed in $\R^m$. Then $\f^{-1}(\R^m\setminus E)$ is closed (relatively) set in $D$. So, $\f^{-1}(\R^m\setminus E) = \f^{-1}(\R^m)\setminus \f^{-1}(E) = D\setminus \f^{-1}(E)$ is closed (relatively) set in $D$. So, $\f^{-1}(E)$ is relatively open in $D$ and this is for all $E$ open in $\R^m$. Thus, $\f\in \C(D)$.
A:
As Reveillark noted: "Your proof seems fine. This is a general fact about arbitrary topological space $f : X \to Y$ is continuous iff $f^{-1}(E)$ is closed in $X$ for every closed $E \subseteq Y$."
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print & to Excel from VBA
I have been trying to code &, as in the character & chr(38), but it keeps underlying the word. any solution for this?
Private Sub createMenu()
'define the variables
Dim mnuDownload1 As Menu
'create the menue bar
With MenuBars(xlWorksheet)
.Reset
.Menus.Add "Import", 1
'define the menue bar
Set mnuDownload1 = MenuBars(xlWorksheet).Menus("Import")
'for each defined menu bar at the sub item , the first "" is the name of the item. The second "" is the macro name
With mnuDownload1.MenuItems
.AddMenu Caption:="P&S"
.Item("P&S").MenuItems.Add "Exclude P" & Chr(38) & "S", "changes"
End With
End With
End Sub
A:
Indeed normal behaviour, one time Chr(38) underlies the next character when busy in the menuitems. A msgbox will display a normal ampersand. If you want to use the ampersand as a character in a menuitem, use it twice as in "Exclude P" & Chr(38) & Chr(38) & "S", or "Exclude P&&S".
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while running a test: "You must add a reference to assembly..."
I am trying to launch a test but I obtain this error
The type 'System.Web.Security.MembershipUser' is defined in an
assembly that is not referenced. You must add a reference to assembly
'System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'.
I looked for google and found that I have to Add Reference System.Web.ApplicationServices to my project, i do it but still dont work.
I wrote it in web.config to but nothig, I obtain the same error
<assemblies>
<add assembly="System.Web.ApplicationServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
Any idea!!! Thanks.
A:
When do you get this problem? When building your project, or when actually running the test?
If you get it when you build your project, follow these steps to see if it resolves your problem:
1 - Search your machine for this file: "System.Web.Security.MembershipUser.dll"
2 - Once you find it, open your project and choose the "Add Reference" menu command
3 - Choose the file you found in step 1
| {
"pile_set_name": "StackExchange"
} |
Q:
How to copy files in Terminal without writing failures?
I have an external HD that has crashed, and is badly corrupted. I want to copy whatever is intact off of it, which means doing so in Terminal as the Finder will of course give up at the first failure.
It's working fine, but taking FOREVER I think because it tries multiple times for any failure. Also on any failed attempt, I end up with the file being written but with zero bytes. So I suppose my question is two fold:
How can I make the cp command try only once and if it fails, move on?
How can I make the cp command not write a file if it was a failed read attempt?
The command I'm currently using is:
sudo cp -Rfn /Volumes/Audio\ HD /Volumes/Audio\ HD\ 2/recovered 2>> /Volumes/iMac\ Storage/cp_errors.txt
Like I said it does work fine, but I really need to speed it up or this is going to take weeks. It's about 400GB of data to read through made up of many small files (and some large ones).
EDIT: I'm running Mac OSX Mountain Lion (latest version)
A:
well, its probably a litte more complicated than that, so try this algorithm:
take an image of the dying disk using DDRescue, and save the image
to another HDD as a file (preferably a very large one).
mount the image in a linux environment, and test it. many of your
files may have been repaired by ddrescue
if the partition is not readable, try TestDisk
if the partition is there but many files are still unrecovered,
abandon the filesystem, and attempt to extract files with tools like
formost, photorec, and magic rescue. these tools cannot recover all
kinds of files (file must have a known header/footer pattern), but
it can get most common binary formats.
Here is a good place to get info on all the tools involved:
https://help.ubuntu.com/community/DataRecovery
http://www.bootmedplus.com/tutorials/image10/
http://www.gnu.org/software/ddrescue/manual/ddrescue_manual.html
http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step
http://www.cgsecurity.org/wiki/PhotoRec_Step_By_Step
http://foremost.sourceforge.net/
| {
"pile_set_name": "StackExchange"
} |
Q:
Triple integrals using spherical co-ordinates
I need to calculate the following:
$ \int_{-2}^{2} \int_{-\sqrt{4-x^2}}^{\sqrt{4-x^2}} \int_{0}^{\sqrt{4-x^2-y^2}} z^2\sqrt{x^2+y^2+z^2} dzdydx $
I sketched this and I can see this is some kind a of a dome, which has ${0\leq z \leq 2}$.
I know how to work with polar coordinates, this seems like a problem fitting for spehrical coordinates, i.e. :
$$ x \to p\sin\phi \cos\theta $$
$$y \to p\sin\phi \sin\theta$$
$$z \to p\cos\phi $$
knowing that $ p = \sqrt{x^2+y^2+z^2} $ I can deduce that ${ 0 \leq p \leq 2}$, but how do I continue to find the angles?
A:
Here, from the integrals, you can easily deduce that:
The function to integrate is $f(x,y,z)=z^2\sqrt{x^2+y^2+z^2}$ and the boundaries to integrate over are: $0 \leq z \leq \sqrt{4-x^2+y^2}$, $\sqrt{4-x^2} \leq y \leq \sqrt{4-x^2}$ and $-2 \leq x \leq 2$.
Basically, you are integrating over a hemisphere of radius 2, which lies on the positive side of the z axis.
So, let
$$ x \to p\sin\phi \cos\theta $$
$$y \to p\sin\phi \sin\theta$$
$$z \to p\cos\phi $$
with the limits $ 0 \leq p \leq 2$, $ 0 \leq \phi \leq \pi/2$ and $ 0 \leq \theta \leq 2\pi$.
So the integral will become,
$ \int_{0}^{2} \int_{0}^{\pi/2} \int_{0}^{2\pi} (p^2\cos^2 \phi)*(p)* p^2\sin \phi \ d\theta d\phi dp$
$= (2\pi) \ \dfrac{p^6}{6}|_{0}^{2} \ \dfrac{-\cos^3 \phi}{3}|_{0}^{\pi/2} $
$=\dfrac{64}{9} \pi$
| {
"pile_set_name": "StackExchange"
} |
Q:
Facebook graph API suddenly going very slow
I'm not really sure what's going on, but today I've noticed that the facebook api is working extremely slow for me.
At first I though it was a bug in my code, but I tried the Graph API Explorer, and even that's causing timeout errors half the time (just using /me):
Failed to load resource: the server responded with a status of 504 (Server timeout)
I don't think its my internet connection, since everything else seems to be working quickly, and http://speedtest.net is giving me good results.
Is my problem somehow fixable or is this just some sort of freak occurance?
Has this happened for anyone else?
Do I need to consider the case that it will take exceedingly long in my application to recieve a response?
I currently have a registration page that waits for a FB.api response (with a spinner gif) before displaying the form. I could use a timeout to wait a few seconds and show it if the api doesn't respond, but I'd really rather not have to use this same sort of logic in every api call that my application depends on...
EDIT: its spontaneously fixed itself now. still no clue what happened.
A:
You can check facebook api live status with this URL
https://developers.facebook.com/live_status
today at 11:13pm: API issues We're currently experiencing a problem
that may result in high API latency and timeouts. We are working on a
fix now.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to imitate two way communication between a brain and a limb?
Human muscles are controlled by action potentials that travel along the nerves. Below is an image of a train of action potentials that are decoded by the brain into a sensation or interpreted by a muscle group as a command.
I'm interested if it is possible to record such action potential sequence and then "play it back" for that person. For example, a person is moving a leg, a recording of action potentials is made. Can such recording be transferred back to the nerves to create an illusion of movement or repeat the muscle movement?
A:
Short answer
Mimicking action potentials is possible, but not the most practical approach.
Background
In general, stimulation of neural tissues occurs through placing electrodes in the vicinity of the target tissue and applying short current pulses, e.g. think cardiac pace makers, cochlear implants, retinal implants (Rao & Chiao, 2015), as well as muscle stimulators.
Long-term electrical stimulation of tissues in humans are accomplished by means of biphasic pulses, such that one phase reverses the current injected by the other. Such alternative current stimuli are called charge-balanced pulses, and are used because direct current (DC) stimulation may damage neural tissues (Bahmer & Baumann, 2013). In animals and short-term applications other asymmetric and unbalanced pulse shapes may be applied.
Secondly, external electrical stimuli induce electric fields such that neurons are depolarized and start firing their own action potentials. Mimicking action potentials doesn't make much sense therefore. It is a more straightforward approach to activate the system externally and let things develop physiologically thereafter to maintain normal neuronal processing.
But of course, in the end you could stick a needle electrode inside neurons and attempt to mimic the voltage changes over time like that in an action potential train, for example through the application of voltage clamp techniques. Nonetheless, I would rather stick to state-of-the-art applications and apply external biphasic pulse trains and leave the details to the neuronal tissue.
References
- Bahmer & Baumann, Hear Res (2013); 306:123-30
- Rao & Chiao, IEEE Microwave Magazine (2015); 16(2): 54-64
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I contact potential referees for a job application?
When applying for an academic position, usually you provide a list of names of people who can give you a reference or letter of recommendation e.g. postdoc advisor or someone you often collaborate with. In this case, obviously you first ask the person if they are willing to do this.
However, for applications to academic positions in some countries, e.g. Switzerland, there's a different system. One is asked to provide the names of potential external referees, i.e. people who work in the same field as you and can evaluate the quality of your scientific output. These are people who don't necessarily know you personally, i.e. the kind of people you would suggest as potential reviewers for one of your articles or grant applications.
My question is this: in the latter case, is it usual or necessary to contact the people before suggesting them as referees? Obviously you wouldn't do so for an article or a grant application, but what about when it's for a job application?
A:
I think the best people to ask would be those who have asked you for this requirement on your job application. There may be a contact in HR or similar you can speak to who can answer any questions you may have, or there may be an online guide on their website for prospective applicants.
If these don't offer any clarification I would suggest not contacting the people you name on your application, just like when recommending reviewers of papers, as this is more or less the sort of role they would be performing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Arduino timer with set/reset buttons
i'm building an automatic hay feeder for my horse,something like this but with just two floors
every 24hrs the plate in the middle should fall and let the hay fall down for the horse to eat,the interface should be very simple,3 buttons one to start the timer, one to stop it and deploy the hay and one to reset the servo in his initial position to lock the plate again, i'm having some problems with the timer,it starts when i press the green button but after it finishes to count it stops and i have to press the green button again, instead it should go endlessly unless i press the red button to reset it
const int greenB = 2;
const int redB = 3;
int inAction = 0;
int greenState = 0;
int redState = 0;
void setup() {
Serial.begin(9600);
pinMode(greenB, INPUT);
pinMode(redB, INPUT);
}
void loop() {
greenState = digitalRead(greenB);
redState = digitalRead(redB);
if(greenState == HIGH){
inAction = 1;
while(inAction == 1){
for(int i = 0; i<10;i++){
if(redState == HIGH){
Serial.println("timer stopped");
goto stopTimer;
}
if(i == 9){
Serial.println("Cycle completed");
}
Serial.println("10 seconds timer");
delay(1000);
}
stopTimer: inAction = 0;
}
}
}
A:
Because you used goto, you caused a problem. Once the code reaches the end of the for loop it will then reach the line labelled stopTimer: and set inAction to 0. That stops everything until you press the green button again.
There is no need to use goto, ever in C++. If you ever find that you want to use goto then you are most likely doing it wrong. Try this instead:
void loop() {
greenState = digitalRead(greenB);
redState = digitalRead(redB);
if(greenState == HIGH){
inAction = 1;
while(inAction == 1){
for(int i = 0; i<10;i++){
if(redState == HIGH){
Serial.println("timer stopped");
inAction = 0;
break; // Ends the for loop right here:
}
if(i == 9){
Serial.println("Cycle completed");
}
Serial.println("10 seconds timer");
delay(1000);
}
}
}
}
When you press the red button, the break statement ends the for loop. It exits right there. It's also the last thing in loop so loop then exits. Next time through loop inAction is set to 0 and that will stop it. But otherwise it just keeps running your 10 second countdown over and over.
There is a lot more you can do to improve this code. Writing it with the delay function means that you may have to hold the button down for up to a second while that line completes before it registers that you pressed it. But that may be a lesson for another day. This will at least show you how goto is bad and why you had the unwanted behavior.
One big improvement would be to let the loop function be your loop and actually make use of your state variable inAction. See if you understannd why this is better: (What if you had some more code that you wanted to run while inAction was 0?)
void loop() {
greenState = digitalRead(greenB);
redState = digitalRead(redB);
if(greenState == HIGH){
inAction = 1;
}
if(inAction == 1){
for(int i = 0; i<10;i++){
if(redState == HIGH){
Serial.println("timer stopped");
inAction = 0;
break; // Ends the for loop right here:
}
if(i == 9){
Serial.println("Cycle completed");
}
Serial.println("10 seconds timer");
delay(1000);
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What is causing my POST request to fail (CORS with Express/Angular)?
At this point, I feel like I've tried everything I can think of and that has been searched.
The "pure" version of my code is as follows:
Server.js - Express
const express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
mongoose = require('mongoose'),
config = require('./DB');
businessRoute = require('../routes/business.route');
mongoose.Promise = global.Promise;
mongoose.connect(config.DB, { useNewUrlParser: true}).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err) }
);
const app = express();
app.use(bodyParser.json());
app.use(cors());
businessRoute.all('*', cors());
app.use('/business', businessRoute);
let port = process.env.PORT || 4000;
const server = app.listen(function(){
console.log('Listening on port ' + port);
});
business.route.js - Express, concat.
const express = require('express');
const app = express();
const businessRoutes = express.Router();
// Require Business model in our routes module
let Business = require('../models/Business');
// Defined store route
businessRoutes.route('/add').post(function(req, res) {
let business = new Business(req.body);
business.save()
.then(business => {
res.status(200).json({'business': 'business added successfully'});
})
.catch(err => {
res.status(400).send("Unable to save to database");
});
});
business.server.ts - Angular
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BusinessService {
uri = 'http://localhost:4000/business';
constructor(private http: HttpClient) { }
addBusiness(person_name, business_name, business_gst_number): void {
const obj = {
person_name: person_name,
business_name: business_name,
business_gst_number: business_gst_number
};
console.log(obj);
this.http.post(`${this.uri}/add`, obj).subscribe(
res => console.log('Done')
);
}
}
What has been Tried
I've attempted to use the following code, which has been recommended on numerous sites, including SO:
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE');
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
I've attempted to remove the cors module for the code, using the attempted solution as a replacement. I used the code in the express router. I've so used both the module and the code in conjuction in both the server.js and router, as well as (and what is still in the code) businessRoute.all('*', cors());
I'm missing something, I have to be. Any help is appreciated.
As requested, here is the network inspector information from Chrome:
And it did give me an OPTIONS error:
A:
I found the issue, thanks to David. The issue was in:
const server = app.listen(port, function(){
console.log('Listening on port ' + port);
});
I was missing port in app.listen().
Thank you for everyone who has helped. I'm inclined to delete the question as it does not have to do with CORS at all, but I was given a warning about deleting questions.
A Request For The Community
Editing the question to something like "Why is Express refusing my API requests?" would be a more accurate question, but make the previously posted answers irrelevant. On top of this, Ebin's answer is unique to all the answers I have seen about the CORS issue, and believe it may help others.
For these reasons, I'm leaving it up to the community and how they feel about the question staying, and if they have any suggestions for improving it to make it worth staying.
| {
"pile_set_name": "StackExchange"
} |
Q:
Declaring multiple variable in url using javascript
I am trying to pass some variables to another page using javascript at present i am passing a single variable in url the url is looks like this
var PageToSendTo = '../xxxx/xxxx.php?appid=4&score='+score;
In at this script score is a javascript variable it is working fine now i want to pass another variable also along with this script
var java_var;
How i am trying to do is something like this
var PageToSendTo = '../xxxx/xxxxx.php?appid=4&score='+score'&javavar='+java_var;
But it is not working properly what is happening here and how to resolve this?.
A:
var PageToSendTo = '../xxxx/xxxxx.php?appid=4&score='+score+'&javavar='+java_var;
Notice +java_var in the end of url.
and yes also according to @Felix + is missing in the url.
| {
"pile_set_name": "StackExchange"
} |
Q:
Recursive Sierpinsky Triangle - StackOverflow error
I got my code running so far, except for the recursive part. I get a StackOverflow error and I really don't get why, or how to fix it. When I work through the code it seems logically fine.
public class SierpinskiTriangle {
public static int SIZE = 1000;
JFrame frame;
JPanel panel;
@SuppressWarnings("serial")
public void display() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel() {
@Override
public void paint(Graphics g) {
super.paint(g);
paintSierpinskiTriangle(20, 20, 360, (Graphics2D)g);
}
};
panel.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
panel.repaint();
}
});
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setSize(SIZE, SIZE);
frame.setVisible(true);
}
public static void main(String[] args) {
SierpinskiTriangle triangle = new SierpinskiTriangle();
triangle.display();
}
public static void paintSierpinskiTriangle(int x, int y, int s, Graphics2D g) {
g.drawLine(x, y, x+s, y);
g.drawLine(x, y, x, y+s);
g.drawLine(x+s, y, x, y+s);
paintSierpinskiTriangle(x, y, s/2, g);
paintSierpinskiTriangle(x+s/2, y, s/2, g);
paintSierpinskiTriangle(x, y+s/2, s/2, g);
}
}
A:
You need to add some conditions to return from the paintSierpinskiTrianglemethod.
Without any conditions, it will keep calling itself infinitely, even if s = 0, which is what causes the Error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating custom captcha in PHP
I want to create my custom Captcha validation in PHP and I have wrote this code but it doesn't seem to be working. The image is not being created and I cannot find where the error is.
PHP:
<?php
session_start();
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$_SESSION['rand_code'] = $string;
//specify the path where the font exists
$dir = 'fonts/arial.ttf';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 200, 100, 90); // red
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);
header("Content-type: image/png");
imagepng($image);
?>
HTML:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p><input type="text" name="name" /> Name</p>
<p><input type="text" name="email" /> Email</p>
<p><textarea name="message"></textarea></p>
<img src="captcha.php"/>
<p><input type="text" name="code" /> Are you human?</p>
<p><input type="submit" name="submit" value="Send" class="button" /></p>
</form>
A:
you generate a warning because of an undefined var..
change this line
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['random_code']);
to this one
imagettftext ($image, 30, 0, 10, 40, $color, $dir."arial.ttf", $_SESSION['rand_code']);
also check, if the font file is really available and readable, or you also will get an warning
| {
"pile_set_name": "StackExchange"
} |
Q:
Add value of button into input field on button click
As I am new to JavaScript. I want to make a calculator, but I am stuck on getting button value into field. Suppose I have following button
<input id='add' type='button' onclick='ik();' value='1'>
and following field
<input type='text' id='one' class='fld'>
Hope I'll get clear with you replies...
A:
You can customize it in anyway you want.
function ik(val){
document.getElementById('one').value = val;
}
<input id='add' type='button' onclick='ik(this.value);' value='1'>
<input type='text' id='one' class='fld'>
And, if you want to add to the current value:
function ik(val){
result = document.getElementById('one');
result.value = result.value? parseInt(result.value) + parseInt(val) : parseInt(val);
}
<input id='add' type='button' onclick='ik(this.value);' value='1'>
<input type='text' id='one' class='fld'>
| {
"pile_set_name": "StackExchange"
} |
Q:
Bejeweled Blitz - How does it assert there is always a move?
I have been playing Bejeweled Blitz for a while now. Yes, it is an addiction. In thinking about the game, I have observed that on some boards, the bottom runs dry (no moves) leaving only the top part of the board playable. Frequently that part of the board drys up, and one is left with moves in area cleared by the last move.
The board never runs completely dry, so clearly the program is doing some sorts of calculation that allows it to choose what to drop to prevent it from running dry.
I have noticed in this 'mode' that it is very common for the algorithm to drop jewels which causes more non-dry area to appear in the horizontal area. Perhaps less frequent is a drop which seems designed to open up the bottom part of the board again.
So my question is "How would one go about designing an algorithm guarantee that there is always a move available.?"
A:
I wrote three-in-a-row game a while ago and the way I dealt with that problem is by selecting gems to drop at random and counting all valid moves. If selected gems did not provide at least 1 valid move I would select another set of gems and so on.
| {
"pile_set_name": "StackExchange"
} |
Q:
base class implementing base interface while derived/concrete class implementing extended interface, why?
I am following a book namely ".NET Domain Driven Design with C#".
Question is based on scenario as shown in Class Diagram below:
Figure:
http://screencast.com/t/a9UULJVW0
In this diagram,
A) IRepository interface is implemented by (abstract base class) RepositoryBase whereas,
B) IRepository interface is also extended by interface ICompanyRepository (ICompanyRepository : IRepository).
C) ICompanyRepository is implemented by CompanyRepository which is derived from SQLRepositoryBase which is derived from RepositoryBase (; which, as stated in point A), implements IRepository which is parent if ICompanyRepository).
D) i create a variable of interface ICompanyRepository having reference to object of clas CompanyRepository, like below:
ICompanyRepository comRep = new Company Repository();
Now, if i call Add() function with ICompanyRepository variable comRep...
comRep.Add();
then Add() function in RepositoryBase class (which is parent of CompanyRepository) is called.
My Question:
What is the exact underlying Object Oriented Rule/Mechanism takes place due to which the function Add() in (abstract-base) class "RepositoryBase" is called? For convenience i am stating below two possible mechanisms: (please tell me which one of two stated below is correct underlying mechanism)
Mechanism-1
Is this Add() function in base class "RepositoryBase" is called because "RepositoryBase" implements IRepoitory ? (Hence making it mandatory for RepositoryBase class to implement IRepository in order to call Add() )
OR
Mechanism-2:
The Add() function in base class "RepositoryBase" is called because CompanyRepository implements ICompanyRepository which implements IRepository which contains definition for Add() function such that when Add() function is called on (with variable of) ICompanyRepository then it first finds the definition of Add in ICompanyRepository and then in parent interface IRepository and then jumps to CompanyRepository class to find implementation of Add() function and not finding the definition of Add() function it traverse upward to parent class SQLRepositoryBase to find Add() function and so on, and as it finds the function Add() in RepositoryBase class so it calls the Add() function in RepositoryBase. This means that if it would have found the Add() function in any of derived classes of RepositoryBase, it had not traverse further upward (in parent class). All of this also means that , in order to traverse from derived class to parent class in chain of classes just to find Add() function, the RepositoryBase class does not really need to inherit directly from IRepository?
There are additional thing in my question and i am unable to understand which OO-Rule is applying in my case as stated below:
In my Question there are two Interfaces one is parent namely IRepository and other is extending it namely ICompanyRepository. Parent interface IRepository contains deifinition of Add() function but not the child interface ICopmanyRepository.
Last derived class in the chain of class Hierarchy "CompanyRepository" implements ICompanyRepository (CompanyRepository does not implement Add() function of IRepository interface) whereas root (top most parent) (abstract base) class namely RepositoryBase implements the Add() function.
So the structure is like the image shown in http://screencast.com/t/a9UULJVW0.
Now if i call Add() function:
codeICompanyRepository lastDerived = new CompanyRepository();
ICompanyRepository->Add();code
Then according to the OO-Rule you stated in you answer, the lookup will start from CompanyRepository class with expectation that CompanyRepository would have implemented Add() function as
code IRepository.Add() {
} //deduced from P17 and P18 in [link] http://www.codeproject.com/Articles/18743/Interfaces-in-C-For-Beginners[link]code
BUT, in my case class CompanyRepository does not have implementation IRepository.Add() { } although the flow of control (while tracing) jumps to Add() function in base class successfully (And code is working fine). I am unable to understand which OO-Rule is applying here ?
Please let me know if you need me to show above scenario with code.
A:
That's a lot of words. I'm going to restate what I think you're asking and answer that question instead. If I'm off the mark, let me know.
When invoking a method through an interface, does it matter if that
interface is explicitly declared again as being implemented on a more derived type
in the type hierarchy?
Yes, this is called "interface re-implementation" and it changes how the method is mapped. The C# language specification (Section 13.4.6 Interface Re-Implementation) goes into this in a little bit more detail, but the gist is that the most derived type that specifies that interface is the starting point for lookup.
interface ICreature
{
void Speak();
}
class Animal : ICreature
{
public void Speak() { Console.WriteLine("Rawr"); }
}
class Duck:Animal
{
public void Speak() { Console.WriteLine("Quack"); }
}
class Human : Animal, ICreature
{
public void Speak() { Console.WriteLine("Hello"); }
}
If you do the following, it will print out "Rawr" and "Hello".
ICreature duck = new Duck();
ICreature human = new Human();
duck.Speak();
human.Speak();
This is because in the Duck hierarchy, the most derived type specifying the ICreature interface is Animal and so it will print out "Rawr".
In the Human hierarchy, the most derived type specifying the ICreature interface is Human (and Human declares an implementation) and so it will print out "Hello". If the Human type had not declared an implementation, it would also have printed "Rawr".
Update
In your specific case, the exact same rule applies. Let's walk through the steps.
ICompanyRepository inherits from IRepository
CompanyRepository declares that it implements ICompanyRepository
CompanyRepository has now implicitly redeclared that it implements IRepository because ICompanyRepository inherits from IRepository
The call chain then follows these steps.
The Add() method is called through the instance typed to the ICompanyRepository interface.
The most derived type that has explicitly declared that it implements IRepository is now CompanyRepository, so lookup begins there.
CompanyRepository does not implement the Add() method directly, so its parent class is inspected.
SQLRepositoryBase is inspected and does not directly implement the method, so its parent class is inspected.
RepositoryBase is inspected and it does implement the method, so that is the method that will be called.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# and Javascript Variable
I have a variable that is like this:
var dependentVar = "'<%: somevalue %>', '<%: somevalue2 %>', '<%: somevalue3 %>'";
Which must be passed into a another variable
var newVar = new var.Function(dependentVar).
The function is like
function(somevalue, somevalue2, somevalue3)
The problem I am facing is that when the variable is passed - it passes like this
"'123123', '123123123', '123123123'"
and it errors due to the " ? How can I fix this ?
A:
Well I wouldn't really do it this way, but you could do this:
var dependentVar = ['<%: somevalue %>', '<%: somevalue %>', '<%: somevalue %>'];
yourfunction.apply(null, dependentVar);
I guess it's not that bad. You could also do
yourfunction(dependentVar[0], dependentVar[1], dependentVar[2]);
The first way does have the advantage that it'd work for any number of values, assuming the function was prepared to deal with that. (If it were, and there were no other reason for the function to be written that way, it could be changed to operate on an array directly.)
edit — OK, if you need to call a function via an object property, you'd do this:
var tmp = new var();
var newVar = tmp.someFunction.apply(tmp, dependentVar);
The first argument to "apply" will make sure that "tmp" is the value of this when "someFunction" is called.
| {
"pile_set_name": "StackExchange"
} |
Q:
drawing a line in Java - line is not visible
I am learning Java on my own. Trying to create a frame with a line in it. It seemed pretty basic, but I can't see the line. The code compiles and I can't seem to understand why I can't see the line. I see other components in the frame.
I am using 2 java files. One file is container file and the other file has the draw line code. They are part of package a1.
Here is my code (please help):
Container File:
package a1;
import javax.swing.*;
import java.awt.*;
public class gameContainer {
public static void addComponentsToPane(Container pane) {
pane.setLayout(null);
//add button to the pane
JButton b3 = new JButton("B1");
pane.add(b3);
//add line to the pane
drawingLine line1 = new drawingLine();
pane.add(line1);
//size and position all relatively
Insets insets = pane.getInsets();
Dimension size;
size = b3.getPreferredSize();
b3.setBounds(350+insets.left,15+insets.top,size.width+50,size.height+20);
size = line1.getPreferredSize();
line1.setBounds(350+insets.left,75+insets.top,size.width+50,size.height+20);
}
private static void createAndShowGUI() {
int l = 200, w = 80;
//Create and set up the window.
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up content pane
addComponentsToPane(frame.getContentPane());
//add menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menu.add(new JMenuItem("Do nothing"));
menuBar.add(menu);
frame.setJMenuBar(menuBar);
// size and display root pane/window
Insets insets = frame.getInsets();
frame.setSize(500+insets.left+insets.right,300+insets.top+insets.bottom);
frame.setLocation(w,l);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Draw line File:
package a1;
import javax.swing.*;
import java.awt.geom.Line2D;
import java.awt.Graphics2D;
import java.awt.Graphics;
public class drawingLine extends JPanel{
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Line2D line = new Line2D.Double(200, 300, 1000, 1000);
//g2d.setColor(Color.black);
g2d.draw(line);
//g.drawLine(200, 300, 1000, 1000);
//g.setColor(color.BLACK);
}
}
Why am I not able to see the line?
A:
Your main problem is that you use null/Absolute layout.
You should have a read here:
Laying Out Components Within a Container
1) You should use an appropriate LayoutManager (or nest together multiple LayoutManagers) and/or override getPreferredSize() of JComponent to return correct dimensions which fit the drawings.
2) Dont call setSize on JFrame rather call pack() before setting JFrame visible (with above in mind)
3) No need for adding to contentPane via getContentPane().add(..) as add(..) setLayout(..) and remove(..) have been forwarded to the contentPane.
4) Watch class names, stick to the java convention a class name begins with a capital letter and each new word thereafter the first letter should be capitilized i.e gameContainer should be GameContainer, drawingLine should be DrawingLine
Here is your code with above fixes implemented (not the most well layed out, but its only an example):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class GameContainer {
public static void addComponentsToPane(JFrame frame) {
JPanel buttonPanel=new JPanel();//create panel to hold button
//add button to the pane
JButton b3 = new JButton("B1");
buttonPanel.add(b3);
frame.add(buttonPanel, BorderLayout.EAST);//use contentPane default BorderLayout
//add line to the pane
DrawingLine line1 = new DrawingLine();
frame.add(line1);
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set up content pane
addComponentsToPane(frame);
//add menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menu.add(new JMenuItem("Do nothing"));
menuBar.add(menu);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class DrawingLine extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Line2D line = new Line2D.Double(10, 10, 100, 100);
g2d.draw(line);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Paint two overlaid JLabels
I want to paint a JLabel over another.
I override paint() so that a second JLabel is painted after calling super.paint().
However this second JLabel is not painted at all (because it is not showing, I think).
How can I achieve that effect?
public class OverlaidJLabel extends JLabel {
private String upperText;
public OverlaidJLabel(){
}
public void setUpperText(String upperText){
this.upperText = upperText;
}
@Override
public void paint(Graphics g){
super.paint(g);
JLabel upperLabel = new JLabel(upperText);
upperLabel.paint(g);
}
}
A:
Some big problems here:
You don't want to override paint in this situation but rather paintComponent
You never want to create components within a painting method. These methods should be for painting and painting only as you'll be creating components many times (since painting methods can be called many times -- and completely out of your control) when they only should be created once, and you don't want to ever slow painting down since this hampers the perceived responsiveness of your GUI.
It makes no sense to create a component that is never added to the GUI, such as your upperLabel. Calling its paint method will achieve absolutely nothing (as you're finding out).
In general, you will want to favor composition over inheritance.
Much better:
If you want to have text on top of text, you could create two JLabels (separately), and place them on top of each other using an appropriate layout manager or using a JLayeredPane.
Or you can do your painting and your painting overlay in a single component, likely the paintComponent override of a JPanel.
For example, one possible overly can use a JLayeredPane that holds two JLabels. A simple example below uses JLabels that hold only text, although you could also implement with ImageIcons, and allow changing each JLabel's font, foreground color, etc...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MyLabel extends JLayeredPane {
// labels to hold texts. label1 is the lower label
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
public MyLabel(String text1, String text2) {
// just so I can see the text separately:
label2.setForeground(Color.RED);
// set text
label1.setText(text1);
label2.setText(text2);
// JPanels to hold the labels. GridBagLayout will center the labels
JPanel baseComponent1 = new JPanel(new GridBagLayout());
JPanel baseComponent2 = new JPanel(new GridBagLayout());
// add labels to the JPanels
baseComponent1.add(label1);
baseComponent2.add(label2);
// have to be able to see through the JPanels
baseComponent1.setOpaque(false);
baseComponent2.setOpaque(false);
// add to the JLayeredPane label2 above label1
add(baseComponent1, JLayeredPane.DEFAULT_LAYER);
add(baseComponent2, JLayeredPane.PALETTE_LAYER);
// If the overall component resizes, resize the
// container base JPanels
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
baseComponent1.setSize(MyLabel.this.getSize());
baseComponent2.setSize(MyLabel.this.getSize());
repaint();
}
});
}
// preferred size depends on the largest dimensions
// of the two JLabels
@Override
public Dimension getPreferredSize() {
Dimension size1 = label1.getPreferredSize();
Dimension size2 = label2.getPreferredSize();
int w = Math.max(size1.width, size2.width);
int h = Math.max(size1.height, size2.height);
return new Dimension(w, h);
}
}
and it can be tested like so:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class MyLabelTest extends JPanel {
public MyLabelTest() {
add(new MyLabel("Test .............................. String 1", "Number 2"));
}
private static void createAndShowGui() {
MyLabelTest mainPanel = new MyLabelTest();
JFrame frame = new JFrame("MyLabelTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
My next iteration would be to add mutator methods to MyLabel to allow changing font, text, and foreground:
public void setFont1(Font font) {
label1.setFont(font);
}
public void setFont2(Font font) {
label2.setFont(font);
}
public void setText1(String text) {
label1.setText(text);
}
public void setText2(String text) {
label2.setText(text);
}
public void setForeground1(Color fg) {
label1.setForeground(fg);
}
public void setForeground2(Color fg) {
label2.setForeground(fg);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why would it be disrespectful to G-d to say Miryam died "al pi Hashem"?
The Torah states that both Moshe (Devarim 34:5) and Aharon (Bamidbar 33:38) died al pi Hashem, by G-d's mouth. Rashi quotes the Talmud (Bava Basra 17a) that this means they died by a neshikah meitah, a "Divine kiss".
When the Torah records the death of Miryam (Bamidbar 20:1) the term al pi Hashem is not used, rather it just plainly says she died. However, Rashi still insists she died from a neshikah meitah, even though the Torah doesn't explicitly say this. He claims that to say Miryam died by G-d's mouth would be disrespectful to the Most High.
I wonder why Rashi would say this would be disrespectful. The only thing I can think of is that Miryam is a woman, and perhaps suggesting G-d "kissed" a woman is disrespectful. However I'm not following that logic. G-d doesn't "kiss" anyone in the physical sense and what's worse about "kissing" a woman versus a man? In fact, in my Americanized mind the thought of kissing a man seems more disrespectful than kissing a woman. Could someone explain Rashi's comment here?
A:
The way your question is phrased makes it seem like the fact that Moshe and Aharon died via "kiss" originates from the Talmud, while the fact that Miriam died via "kiss" and that it would be improper to write this are Rashi's own additions. In fact all of this is in the Talmud, so to whatever extent you have a question it is on the Talmud not on Rashi.
Bava Batra 17a
תנו רבנן ששה לא שלט בהן מלאך המות ואלו הן אברהם יצחק ויעקב משה אהרן
ומרים אברהם יצחק ויעקב דכתיב בהו בכל מכל כל משה אהרן ומרים דכתיב בהו
על פי ה' והא מרים לא כתיב בה על פי ה' אמר ר"א מרים נמי בנשיקה מתה
דאתיא שם שם ממשה ומפני מה לא נאמר בה על פי ה' שגנאי הדבר לומר
Our Rabbis taught: Six there were over whom the Angel of Death had no
dominion, namely, Abraham, Isaac and Jacob, Moses, Aaron and Miriam.
Abraham, Isaac and Jacob we know because it is written in connection
with them, in all, of all, all; Moses, Aaron and Miriam because it is
written in connection with them [that they died] By the mouth of the
Lord. But the words ‘by the month of the Lord’ are not used in
connection with [the death of] Miriam? — R. Eleazar said: Miriam also
died by a kiss, as we learn from the use of the word ‘there’ [in
connection both with her death] and with that of Moses. And why is it
not said of her that [she died] by the month1 of the Lord? — Because
such an expression would be disrespectful. (Soncino translation)
While the Talmud does not state what the disrespect is, there are parallel versions of this teaching in other Midrashic sources. In one of them, it explicitly states that the disrespect is to use the term when speaking of a woman:
Yalkut Shimoni Parshat Chayei Sarah
ששה לא שלט בהן מלאך המות אברהם יצחק ויעקב דכתיב בהו בכל מכל כל משה
אהרן ומרים דכתיב בהו ע"פ ה' ומרים אע"ג דלא כתיב בה אתיא שם שם ממשה
ומפני מה לא נאמר בה שגנאי הדבר לומר אצל אשה
Similarly, in the version recorded in Yalkut Midrashei Teiman (on the pasuk of Miriam's death) there is no mention of disrespect but it states that the reason why the Torah doesn't say "by the mouth of God" buy Miriam is that she was a woman:
שלשה מתו בנשיקה משה ואהרן ומרים נאמר במשה על פי ה' שנאמר וימת שם משה
עבד ה' ונאמר באהרן על פי ה' שנאמר וימת אהרן שם בהר ההר ונאמר במרים
ותמת שם מרים ותקבר שם [ומפני שהיא אשה] לא נאמר בה על פי ה
Rambam, too, assumes the disrespectful aspect is that Miriam was a woman:
Guide for the Perplexed 3:51
Our Sages said that the same was the case with Miriam; but the phrase
"by the mouth of the Lord" is not employed, because it was not
considered appropriate to use these words in the description of her
death as she was a female. (Friedlander translation)
R. Yosef Chaim of Baghdad explains this explicitly:
Ben Yehoyada Bava Batra 17a
ועם כל זה לא נקיט כן להדיא במרים דאף על גב דהוא דרך משל ודמיון עם כל
זה גנאי הדבר למנקט לשון זה של נשיקת פה בנקבה
And all this notwithstanding, it does not use this [terminology] explicitly by
Miriam because even though it is metaphorical it is still degrading to
use the terminology of a mouth-kiss by a woman.
It seems that the "disrespect" is the association of the erotic connotation of kissing a woman with God. That is to say that it is not the erotic connotation of kissing a woman on it's own that is deemed inappropriate for the Torah to discuss; indeed, R. Chaim Hirschensohn notes that the Torah had no problem describing Yaakov kissing Rachel:
Nimukei Rashi 4:381
אם שהנשיקה בעצמה איננה נגד נימוס הכבוד דכתיב וישק יעקב לרחל אבל לזכור
על פי ה' איננו דרך כבוד
Rather it is the association of God with the eroticness that is inappropriate.
Similarly, Shir Hashirim is replete with eroticness but it is not problematic because the eroticness is not associated with God (in the text).
1. This is clearly a typo, and should say "mouth". It appears with the word as "month" in the PDF (linked) but I don't know how it appears in the original printed volume.
| {
"pile_set_name": "StackExchange"
} |
Q:
Issue with computing gradient for Rnn in Theano
I am playing with vanilla Rnn's, training with gradient descent (non-batch version), and I am having an issue with the gradient computation for the (scalar) cost; here's the relevant portion of my code:
class Rnn(object):
# ............ [skipping the trivial initialization]
def recurrence(x_t, h_tm_prev):
h_t = T.tanh(T.dot(x_t, self.W_xh) +
T.dot(h_tm_prev, self.W_hh) + self.b_h)
return h_t
h, _ = theano.scan(
recurrence,
sequences=self.input,
outputs_info=self.h0
)
y_t = T.dot(h[-1], self.W_hy) + self.b_y
self.p_y_given_x = T.nnet.softmax(y_t)
self.y_pred = T.argmax(self.p_y_given_x, axis=1)
def negative_log_likelihood(self, y):
return -T.mean(T.log(self.p_y_given_x)[:, y])
def testRnn(dataset, vocabulary, learning_rate=0.01, n_epochs=50):
# ............ [skipping the trivial initialization]
index = T.lscalar('index')
x = T.fmatrix('x')
y = T.iscalar('y')
rnn = Rnn(x, n_x=27, n_h=12, n_y=27)
nll = rnn.negative_log_likelihood(y)
cost = T.lscalar('cost')
gparams = [T.grad(cost, param) for param in rnn.params]
updates = [(param, param - learning_rate * gparam)
for param, gparam in zip(rnn.params, gparams)
]
train_model = theano.function(
inputs=[index],
outputs=nll,
givens={
x: train_set_x[index],
y: train_set_y[index]
},
)
sgd_step = theano.function(
inputs=[cost],
outputs=[],
updates=updates
)
done_looping = False
while(epoch < n_epochs) and (not done_looping):
epoch += 1
tr_cost = 0.
for idx in xrange(n_train_examples):
tr_cost += train_model(idx)
# perform sgd step after going through the complete training set
sgd_step(tr_cost)
For some reasons I don't want to pass complete (training) data to the train_model(..), instead I want to pass individual examples at a time. Now the problem is that each call to train_model(..) returns me the cost (negative log-likelihood) of that particular example and then I have to aggregate all the cost (of the complete (training) data-set) and then take derivative and perform the relevant update to the weight parameters in the sgd_step(..), and for obvious reasons with my current implementation I am getting this error: theano.gradient.DisconnectedInputError: grad method was asked to compute the gradient with respect to a variable that is not part of the computational graph of the cost, or is used only by a non-differentiable operator: W_xh. Now I don't understand how to make 'cost' a part of computational graph (as in my case when I have to wait for it to be aggregated) or is there any better/elegant way to achieve the same thing ?
Thanks.
A:
It turns out one cannot bring the symbolic variable into Theano graph if they are not part of computational graph. Therefore, I have to change the way to pass data to the train_model(..); passing the complete training data instead of individual example fix the issue.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I connect a sensor to two LEDs so that one will work when the sensor's output is HIGH and the other when it's LOW?
(Moved from the Arduino stackexchange)
Let OUT be the sensor's output.
If I connect
LED1 to BAT+ and OUT
LED2 to BAT- and OUT
is this Ok?
Instead of LEDs those could be units that need even less current. I am also interested to know the limits of the offered solution in terms of current and what should I do from units that draw higher current.
Anyway, I look for a solution without a MCU.
A:
Figure 1. Source: One GPIO, multiple LEDs.
When the output is switched low current will flow from the positive supply via R1 and the L1, green, to the output pin. L1 will illuminate. L2, red, will be shorted out and will be dark.
When the output is switched high current will flow from the pin through R2 and L2. The red LED will illuminate and the green will be dark.
If the output is tri-stated (wired as an input or disconnected by program control) a current will flow through R1, L1, R2, L2 and both LEDs will glow dimly. On a 3.3 V device the voltage wouldn’t be high enough to illuminate both LEDs significantly so they would appear dark.
By rapidly (> 25 Hz should be enough) alternately switching the output high and low while varying the duty-cycle a cross-fade effect can be given.
See the linked article for more on the subject.
A:
Your solution is acceptable within limitations:
Voltage swing of Out needs to be >= Vf = LED on voltage (no surprise)
Vsupply needs to be much less than Vf (LED on voltage). If Vsupply is too high both LEDs will light noticeably when OUT is open circuit.
In almost any real-world case you will get some LED current when OUT is open circuit. This may or may not be acceptable.
OUT needs to be able to source and sink the required LED current.
A resistor is provided between the centre point of the two LEDS and OUT to control LED current.
R1 is sized to suit desired LED current drain.
More can be said but start with the above and ask/comment as required.
simulate this circuit – Schematic created using CircuitLab
___________________________
For higher current than the I/O pin can source or sink a buffer or driver is required. This can be an IC suited to the task or a discrete transistor circuit.
This circuit will work "as shown" with some limitations.
Q1 / Q2 draw a current spike at changeover from high to low and VOUT should not be left open-circuit.
Q1 / Q2 can be any small bipolar transistor with adequate voltage and current characteristrics.
R1 is sized to suit desired LED current drain.
simulate this circuit
| {
"pile_set_name": "StackExchange"
} |
Q:
How to perform navigation from UIView to ViewController
In my home screen have multiple sections of UICollectionView so I used separate - separate views(xib) for each section(UICollectionViews) now I have to perform navigation(didSelectItemAt) I am unable to perform it even no error is there
I user below code for navigation(didSelectItemAt)
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = UIStoryboard.init(name: "ProductListing", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProductListingViewController") as? ProductListingViewController
(superview?.next as? ProductListingViewController)?.navigationController?.pushViewController(vc!, animated: true)}
A:
You can use callbacks for this.
In your collectionView View add this callBack :
var didSelectCallback: (() -> Void)?
Then in didSelectItem delegate method of collectionView write this :
if let callBack = didSelectCallback {
callBack()
}
Then in controller when you add this collectionView View add this callBack :
yourView.didSelectCallback = { [weak self] in
guard let weakSelf = self else {return}
let vc = UIStoryboard.init(name: "ProductListing", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProductListingViewController") as? ProductListingViewController
weakSelf.navigationController?.pushViewController(vc!, animated: true)}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
ambiguous template overload for template parameter is a container
Please consider the following example:
#include <string>
#include <vector>
using std::string;
using std::vector;
template <typename T>
const T GetValue()
{
return T(); // some value
}
template <typename T>
const vector<T> GetValue()
{
return vector<T>(); // some vector of values
}
int main(int argc, char* argv[])
{
int i = GetValue<int>();
vector<int> = GetValue<vector<int>>();
return 0;
}
I have two template functions which are supposed to parse values from some storage depending on an given type. The first should do the job for simple data types, the second for vectors of simple data types only.
My problem is that the template matching is ambiguous since T may be vector<T>.
I wonder how to implement the overload/specialization for the vector types properly.
Any help would be greatly appreciated!
A:
One simple way is to use an out-param, so that the template parameter can be deduced from the argument:
#include <vector>
using std::vector;
template <typename T>
void GetValue(T &t)
{
t = T(); // some value
}
template <typename T>
void GetValue(vector<T> &v)
{
v = vector<T>(); // some vector of values
}
int main(int argc, char* argv[])
{
int i;
GetValue(i);
vector<int> v;
GetValue(v);
return 0;
}
GetValue(v) isn't ambiguous, since the template argument deduction rules say that the second overload is the better match.
This isn't necessarily the interface/style you want, though, in which case you could use partial specialization instead of overloading. But that requires a class, since function templates cannot be partially specialized:
#include <vector>
using std::vector;
template <typename T>
struct Getter {
T get(void) {
return T(); // some value
}
};
template <typename T>
struct Getter<vector<T> > {
vector<T> get(void) {
return vector<T>(); // some vector of values
}
};
template <typename T>
T GetValue(void)
{
return Getter<T>().get();
}
int main(int argc, char* argv[])
{
int i = GetValue<int>();
vector<int> v = GetValue<vector<int> >();
return 0;
}
A:
Both version ofGetValue differs by only return type, hence it is not overload.
I would suggest you to have just one GetValue and then implement two functions which differ by parameter type, as opposed to return type, and forward the call as:
namespace details
{
template <typename T>
T FillValue(T*)
{
//your code
}
template <typename T>
vector<T> FillValue(vector<T> *)
{
//your code
}
}
template <typename T>
T GetValue()
{
return details::FillValue((T*)0); //pass null pointer of type T*
}
The correct FillValue will be selected by the compiler based on the type of the argument passed to the function, which is T*. If T is vector<U> for some type U, then the second function will be selected, otherwise the first function will be selected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Visual Studio editing of JSX
I am using Visual Studio 2013 to build a website that uses React and JSX for the user interface. This all works fine but makes for a slow development environment because the .jsx files are treated as plain text. So no syntax highlighting and you cannot set break points to help debugging.
Is there a way to improve this experience or do I have to switch to another editor for the jsx files?
A:
Two tricks I can recommend:
1) You can make Visual Studio display a .jsx file with javascript formatting. In Visual Studio open Tools > Options > Text Editor > File Extensions. Set extension to "jsx" and select the javascript editor and click "Add". You may need to close and reopen VS to see the changes. If you keep your render() method at the bottom of your .jsx file, it works pretty well.
2) Breakpoints: no, you can't add them ahead of time, but there is a workaround. When you run your web app in Visual Studio, a new folder opens up in your Solution Explorer window named "Script Documents." The code from your transformed .jsx files are joined together into this "script block" file. You can add breakpoints here after starting the web app in Visual Studio, once the web page has loaded.
Admittedly, these breakpoints are lost as soon as your stop the debugger. The next time you run your program, you have to set them again. But at least you can get your foot in the door.
If you want to break into the code that has already run before the web page is full loaded, add an alert("here"); command in the jsx just before the line you want to break into. Run the code, and when the popup appears, don't press OK. Switch to the VS debugger, add your breakpoint in the script block file, and then press the OK button. The code should stop immediately on your breakpoint.
| {
"pile_set_name": "StackExchange"
} |
Q:
Gson, how to deserialize array or empty string
I trying to deserialize this json to array of objects:
[{
"name": "item 1",
"tags": ["tag1"]
},
{
"name": "item 2",
"tags": ["tag1","tag2"]
},
{
"name": "item 3",
"tags": []
},
{
"name": "item 4",
"tags": ""
}]
My java class looks like this:
public class MyObject
{
@Expose
private String name;
@Expose
private List<String> tags = new ArrayList<String>();
}
The problem is json's tags property which can be just empty string or array. Right now gson gives me error: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
How should I deserialize this json?
I do not have any control to this json, it comes from 3rd pary api.
A:
I do not have any control to this json, it comes from 3rd pary api.
If you don't have the control over the data, your best solution is to create a custom deserializer in my opinion:
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
@Override
public MyObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject jObj = json.getAsJsonObject();
JsonElement jElement = jObj.get("tags");
List<String> tags = Collections.emptyList();
if(jElement.isJsonArray()) {
tags = context.deserialize(jElement.getAsJsonArray(), new TypeToken<List<String>>(){}.getType());
}
//assuming there is an appropriate constructor
return new MyObject(jObj.getAsJsonPrimitive("name").getAsString(), tags);
}
}
What it does it that it checks whether "tags" is a JsonArray or not. If it's the case, it deserializes it as usual, otherwise you don't touch it and just create your object with an empty list.
Once you've written that, you need to register it within the JSON parser:
Gson gson = new GsonBuilder().registerTypeAdapter(MyObject.class, new MyObjectDeserializer()).create();
//here json is a String that contains your input
List<MyObject> myObjects = gson.fromJson(json, new TypeToken<List<MyObject>>(){}.getType());
Running it, I get as output:
MyObject{name='item 1', tags=[tag1]}
MyObject{name='item 2', tags=[tag1, tag2]}
MyObject{name='item 3', tags=[]}
MyObject{name='item 4', tags=[]}
| {
"pile_set_name": "StackExchange"
} |
Q:
create unique combination of characters from same array in java
I have a string array = String[] str = {"a","b","c","d"} that I want o multiply with itself thrice to get triplets in this form = {a,b,c}..and so on.
I wrote this code:
String[] str = {"a","b","c","d"};
for(int i=0; i<str.length;i++){
for(int j=1;j<str.length;j++){
for(int k=2; k<str.length;k++){
System.out.println(str[i]+"_"+str[j]+"_"+str[k]);
}
}
}
But the output I get looks like this:
a_b_c
a_b_d
a_c_c
a_c_d
a_d_c
a_d_d
b_b_c
b_b_d
I want only unique combinations: a_b_c, a_b_d, a_c_d, b_c_d
Can I get some help here please?
A:
You can skip repeated strings by using continue if you're processing elements that are equal.
String[] str = {"a","b","c","d"};
for (int i = 0; i < str.length; i++) {
for (int j = 1; j < str.length; j++) {
if (str[j].equals(str[i]))
continue;
for (int k = 2; k < str.length; k++) {
if (str[k].equals(str[i]) || str[k].equals(str[j]))
continue;
System.out.println(str[i] + "_" + str[j] + "_" + str[k]);
}
}
}
If you know that str does not contain duplicate elements (or if you want to include duplicates in that case), then you can skip based on equality of indices rather than elements:
for (int i = 0; i < str.length; i++) {
for (int j = 1; j < str.length; j++) {
if (i == j)
continue;
for (int k = 2; k < str.length; k++) {
if (i == k || j == k)
continue;
System.out.println(str[i] + "_" + str[j] + "_" + str[k]);
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Loading GLSL shader without using any Apple APIs
What is a good way to load a GLSL shader using C/C++ without using Objective-C or any Apple APIs?
I am currently using the following method, which is from the iPhone 3D Programming book, but it says that it is not recommended for production code:
Simple.vsh
const char* SimpleVertexShader = STRINGIFY
(
// Shader code...
);
RenderingEngine.cpp
#define STRINGIFY(A) #A
#include "Simple.vsh"
// ...
glShaderSource( shaderHandle, 1, &SimpleVertexShader, 0 );
A:
If you want to load your shaders from files in your app bundle, you can get the file paths using the NSBundle object (in Objective-C), or using the CoreFoundation CFBundle object (in pure C).
Either way, you are using Apple-specific APIs. The only thing you're getting by using CFBundle instead of NSBundle is more boilerplate code.
If you don't want to use any Apple APIs, then your options are to embed your shaders as literal strings, or connect to a server on the Internet and download them (using the Unix socket API).
What you really need to do is define an interface by which your RenderingEngine gets the source code for its shaders, and implement that interface using the appropriate platform-specific API on each platform to which your port the RenderingEngine. The interface can be something super simple like this:
RenderingEngineShaderSourceInterface.h
#ifdef __cplusplus
extern "C" {
#endif
// You are responsible for freeing the C string that this function returns.
extern char const *RenderingEngine_shaderSourceForName(char const *name);
#ifdef __cplusplus
}
#endif
Then you create RenderingEngineShaderSource_Windows.cpp, RenderingEngineShaderSource_iOS.m, RenderingEngineShaderSource_Linux.cpp, etc. Each one implements RenderingEngine_shaderSourceForName using the appropriate API for that platform.
| {
"pile_set_name": "StackExchange"
} |
Q:
How use export in an HTML
When I have extern javascript file with an export-statement how can I call this in an HTML ?
An import in a <script> tag also doesn't work.
an include over the <head> gives me a "Unexpected token export" error
For example:
my extern js-File
export function myFunction(text) { return text; }
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="myExternFile.js"> </script>
</head>
<body>
<script>
console.log(myFunction("some text"));
</script>
</body>
</html>
A:
According to ECMAScript modules in browsers you can do it with <script type="module">
<script type="module">
import {myFunction} from './myExternalFile.js';
console.log(myFunction("some text"));
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
Using two patterns - One for warn and above. One for everything below
How can I set up log4j to use two separate patterns based on the logging level of the message?
For example, right now I'm using the following which applies to all levels:
log4j.appender.stdout.layout.ConversionPattern=%-5p %d{HH\:mm\:ss} - %m%n
What I'd like to do is use a different pattern for levels of WARN and above. Such as:
%-5p %d{HH\:mm\:ss} - [%L:%C] %m%n
To output the line number and class where the warning or error occurred. The extra cost of pulling the caller information would be worth it in situations where a warning or error occurs.
Is this doable?
Here is my full log4j.properties file:
log4j.rootLogger=WARN, stdout1, stdout2
log4j.category.my.package=DEBUG
log4j.appender.stdout1=org.apache.log4j.ConsoleAppender
log4j.appender.stdout1.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout1.layout.ConversionPattern=%-5p %d{HH\:mm\:ss} - %m%n
log4j.appender.stdout2=org.apache.log4j.ConsoleAppender
log4j.appender.stdout2.threshold=WARN
log4j.appender.stdout2.target=System.err
log4j.appender.stdout2.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout2.layout.ConversionPattern=%-5p %d{HH\:mm\:ss} - [%t] [%L:%C] %m%n
EDIT
threshold looks to be what I need to log all levels of WARN and higher. Is there a similar property that will configure the other appender to log all levels of INFO and lower?
A:
Found the answer here: Logging error to stderr and debug, info to stdout with log4j
I ended up having to use an xml file instead of a properties file to get the results that I want.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
<!-- STDERR - WARN and above -->
<appender name="stderr" class="org.apache.log4j.ConsoleAppender">
<param name="threshold" value="warn" />
<param name="target" value="System.err"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{HH\:mm\:ss} - [%t][%L:%C] %m%n" />
</layout>
</appender>
<!-- STDINFO - DEBUG & INFO -->
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<param name="threshold" value="debug" />
<param name="target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %d{HH\:mm\:ss} - %m%n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="debug" />
<param name="LevelMax" value="info" />
</filter>
</appender>
<category name="my.project.package">
<!-- Display DEBUG and above for all log messages in My Project -->
<param name="level" value="debug" />
</category>
<root>
<!-- Global Setting - Display only WARN messages
This surpresses other libraries from display DEBUG & INFO messages
But the Category setting above for your project will override this
and display DEBUG & INFO messages (using STDOUT) as well as
WARN and above (using STDERR) -->
<priority value="warn"></priority>
<appender-ref ref="stderr" />
<appender-ref ref="stdout" />
</root>
</log4j:configuration>
| {
"pile_set_name": "StackExchange"
} |
Q:
timer implementd on fd
To implement a timer, I'm currently forking a process that uses SIGALRM to periodically wake it and write a byte into a pipe. I'm aware of signalfd for receiving signals on a file descriptor and I'd like to do the same with a timer, but all of the timer mechanisms I'm aware of use signals. Does Linux provide a mechanism to provide a timer via a file descriptor?
A:
You could use timerfd_create and friends. It is a linux specific syscall.
| {
"pile_set_name": "StackExchange"
} |
Q:
Consuming JSON in play! framework controller
I'm trying to consume a JSON array I created using JavaScript but the array is never bound in my controller
Here is the JavaScript code I use to call my controller action
$.post("/produits_ajax",{filterParams:[{name:"milk", value:"chevre"}, {name:"pate", value:"molle"}]},
function(data){
$('.dynamicContent').html(data);
slideProducts();
// initialize scrollable
$(".scrollable").scrollable();
});
My routes file entry
POST /produits_ajax Application.produitsAjax
Here is how I receive it in my play! controller. I'm using play 1.1 and the JsonArray is from com.google.gson.JsonArray
public static void produitsAjax(JsonArray filterParams) {
if(filterParams != null)
Logger.debug("Le Json: " + filterParams.toString());
else
Logger.debug("filterParams is null");
render();
}
As you can imagine I always get "filterParams is null" in my console (I wouldn't be writhing this if I wasn't)
It's very basic so far I just want to bind the array generated in JS to my JsonArray. Play!framework has a great documentation but for some reason there is very little on this particular subject.
If anyone can shed some light on this It would be much appreciated
A:
You just have to create a TypeBinder class to add JsonObject binding capacity to Play!. Actually, that's pretty easy to achieve in Play 1.2. Here's the complete class:
@Global
public class JsonObjectBinder implements TypeBinder<JsonObject> {
@Override
public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) throws Exception {
return new JsonParser().parse(value);
}
}
That's it! With the @Global annotation, Play will find it at load time and register this with the other binders. I use this in my controller with the following signature :
public static void handleJsonBody(JsonObject body) {
...
}
The body will be automatically parsed by Play. You can do the same for JsonArray to support your particular case.
A:
You have 2 options:
simple one: pass the parameter as a String and in the controller parse it to Json
complex one: create your own binder using TypeBinder
| {
"pile_set_name": "StackExchange"
} |
Q:
A Voynichian Challenge
Background: what follows is not a foreign language. Rather, it is a symbol-based code of English. You could think of it as falling between semaphore flags, which use a symbol per letter, and Shavian, which is based on English phonology.
Vague Hint:
Each line translates to a line out of Daffodils, The Tyger, and A Psalm of Life
A slightly more complex piece of writing
A:
With the huge vague hint, I think these are:
I wandered lonely as a cloud
In the forests of the night
Life is but an empty dream
In the annotated picture below
The red circles are
as, a, is, an
The blue circles are
the L sound in LONELY, CLOUD, LIFE
The green circles are
the T sound in FORESTS, NIGHT, BUT, EMPTY
The black circles are
the AI diphthong in I, NIGHT, LIFE
The brown circles are
the M sound in EMPTY and DREAM
Other cues:
the N in NIGHT and IN is the same as the N in AN
the symbol for THE
| {
"pile_set_name": "StackExchange"
} |
Q:
UIButton color issues
How can I change the color of the text on my UIButton. Here is my current code:
UIButton *b1 = [[UIButton alloc] init];
b1.frame = CGRectMake(280,395,30,30);
[[b1 layer] setCornerRadius:8.0f];
[[b1 layer] setMasksToBounds:YES];
[[b1 layer] setBorderWidth:1.0f];
[[b1 layer] setBackgroundColor:[botCol CGColor]];
b1.titleLabel.font = [UIFont boldSystemFontOfSize:24];
[b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents];
[b1 addTarget:self action:@selector(NextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b1 setTitle:@">" forState:UIControlStateNormal];
[self.view addSubview:b1];
Here is what it looks like (ignore the background color and stuff):
Now, how can I get the arrow to be red? As you see above, I already have the following:
[b1 setTitleColor:[UIColor redColor] forState:UIControlEventAllEvents];
but it isn't working.
A:
Try setting the individual events, such as:
[b1 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
| {
"pile_set_name": "StackExchange"
} |
Q:
BottomNavigationView only hiding on scroll for one fragment
I have a BottomNavigationView in my activity_main.xml, along with a FrameLayout to swap between 3 fragments.
I'm using CoordinatorLayout.
I'm trying to make it so that when the fragment in the FrameLayout is scrolled, the navigation bar hides itself.
I've added the behaviour attribute to the the nav bar in my layout, and it's working for the first fragment, which is a RelativeLayout with a RecyclerView in it.
However, when I switch the a different fragment, which is a ScrollView, the nav bar no longer hides itself.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainLayout"
android:background="@color/colorMain"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_alignParentTop="true"
android:id="@+id/mainPaddingTop"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
<FrameLayout
android:layout_below="@id/mainPaddingTop"
android:layout_above="@id/mainPaddingBottom"
android:id="@+id/frag_container"
android:clipToPadding="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<View
android:visibility="visible"
android:layout_alignParentBottom="true"
android:id="@+id/mainPaddingBottom"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
</RelativeLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
android:id="@+id/fab"
android:layout_marginBottom="74dp"
android:layout_gravity="end|bottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:rippleColor="@color/colorPrimary"
android:clickable="true"
android:layout_marginEnd="18dp"
android:tint="@color/colorMain"
app:srcCompat="@drawable/ic_plus" />
<androidx.appcompat.widget.Toolbar
android:minHeight="?attr/actionBarSize"
android:layout_gravity="top"
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:elevation="1dp"
android:background="@color/colorMain">
<ImageButton
android:id="@+id/accountButton"
android:layout_gravity="end"
android:tint="@color/colorSecondary"
android:background="?attr/selectableItemBackgroundBorderless"
app:srcCompat="@drawable/ic_account"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:contentDescription="@string/account" />
<ImageButton
android:visibility="gone"
android:id="@+id/searchButton"
android:layout_gravity="start"
android:tint="@color/colorSecondary"
android:background="?attr/selectableItemBackgroundBorderless"
app:srcCompat="@drawable/ic_magnify"
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:contentDescription="@string/account" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_title"
android:textColor="@color/colorSecondary"
android:fontFamily="@font/productsansmedium"
android:textSize="20sp"
android:layout_gravity="center"
android:id="@+id/toolbar_title" />
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_gravity="bottom"
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior"
android:theme="@style/Widget.BottomNavigationView"
android:background="@color/bottomNavColor"
app:itemIconTint="@drawable/navbar_color_selector"
app:itemTextColor="@drawable/navbar_color_selector"
app:elevation="26dp"
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_nav_items" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
fragment_start.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".StartFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:scrollbars="none" />
</RelativeLayout>
fragment_centre.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:scrollbars="none"
android:descendantFocusability="blocksDescendants"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".CentreFragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginStart="16dp"
android:layout_marginTop="12dp"
android:textSize="12sp"
android:fontFamily="@font/productsansmedium"
android:textColor="@color/colorSecondary"
android:text="@string/section_1"
android:id="@+id/section1Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_marginStart="16dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:textSize="12sp"
android:layout_below="@id/horizontalScroll"
android:fontFamily="@font/productsansmedium"
android:textColor="@color/colorSecondary"
android:text="@string/section_2"
android:id="@+id/section2Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<LinearLayout
android:orientation="vertical"
android:layout_below="@id/section2Text"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_1" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_2" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_3" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_4" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_5" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_6" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_7" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
<LinearLayout
android:clickable="true"
android:focusable="true"
android:foreground="?attr/selectableItemBackground"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.card.MaterialCardView
android:layout_margin="16dp"
app:strokeWidth="1.5dp"
app:strokeColor="@color/colorQuad"
app:cardElevation="0dp"
app:cardBackgroundColor="@color/colorMain"
app:cardCornerRadius="28dp"
android:layout_width="38dp"
android:layout_height="38dp">
<ImageView
android:tint="@color/colorSecondary"
android:layout_gravity="center"
android:src="@drawable/ic_folder_pound"
android:layout_width="22dp"
android:layout_height="22dp"/>
</com.google.android.material.card.MaterialCardView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center_vertical"
android:textSize="16sp"
android:textColor="@color/colorFont"
android:fontFamily="@font/productsansmedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/category_8" />
<ImageView
android:layout_gravity="bottom|start"
android:tint="@color/colorQuad"
android:src="@drawable/line_seperator"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</FrameLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
</ScrollView>
The result is that when I scroll in the second fragment, the bar doesn't hide itself and covers up the bottom of the fragment.
A:
Use NestedScrollView instead of ScrollView.
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/hide_bottom_view_on_scroll_behavior">
<!-- Your scrolling content -->
</android.support.v4.widget.NestedScrollView>
Hope it solves.
| {
"pile_set_name": "StackExchange"
} |
Q:
sed: remove numbers from file
I'm trying to remove all words from a file that contain a number
Attempt
sed -r 's/\w*\d\w*//g' file.txt
Sample file.txt:
12.23 worda
01234 wordb
wordc
fe424 wordd
a232efe424 worde 7
a232efe424 wordf wordg 7
a232efe424 wordh h5f
Desired ouput:
worda
wordb
wordc
wordd
worde
wordf wordg
wordh
A:
sed oneliner
sed -r 's/[^[:space:]]*[0-9][^[:space:]]* ?//g'
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding some fields in existing membership method
How I can add a product id in asp.net membership with existing method of create user or something like that. Need following thing with membership like that >>
Membership.CreateUser(Username, Password , Product id ( need a method to add it ))
Roles.AddUserToRole(Username, "some roles")
Samemethod.add(username, productid)[ addition for adding the product it ]
A:
Need following thing with membership like that >>
Membership.CreateUser(Username, Password , Product id ( need a method
to add it ))
The answer is you cannot. Membership is based on Provider Model. You cannot add/remove parameters to Membership's Methods.
In addition, you cannot add/remove columns of Membership's tables. Look at this answer.
Work Around
You need to create user using Membership.CreateUser method. Then use the newly inserted userId to add productId.
MembershipCreateStatus status;
MembershipUser membershipUser = Membership.CreateUser("Username",
"Password", "Email", "PasswordQuestion",
"PasswordAnswer", IsApproved, out status);
if (status == MembershipCreateStatus.Success)
{
Guid userId = (Guid)membershipUser.ProviderUserKey;
// Insert product id here.
}
FYI: Membership Provider has been deprecated few years ago. If you are working on a new application, you might want to look at new ASP.Net Identity 2.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wrong login dialog after meddling with xrdp and various desktops
After I've been meddling with xrdp for quite a while, trying mint, xfce4 and xubuntu as xrdp desktop environment, I have my login dialog changed to this. I can neither tell which desktop environment part it is nor what package should I remove or reinstall to fix it.
A:
This article helped: Restore Unity Greeter
In short:
Now on a new install of Ubuntu 14.10 + xubuntu-desktop on top of that, there is no directory lightdm.conf.d under /etc/lightdm. But following advice from here I created the directory /etc/lightdm/lightdm.conf.d and a file /etc/lightdm/lightdm.conf.d/50-myconfig.conf with contents
[SeatDefaults]
greeter-session=unity-greeter
and I get the unity greeter back.
| {
"pile_set_name": "StackExchange"
} |
Q:
getTitleTooltip method is not getting called once we mouse over in an Eclipse Editor
I have a RCP application where I implemented an Editor by following way-
public class CheckView extends EditorPart implements IMessageView,IViewPart {
Now I override the method getTitleToolTip() method and did some operation which will give different tooltips on different conditions. But the problem is , only once the getTooltip method is getting called , when we launch the RCP tool. But it should always get called whenever we mouseover the editor.
Whats going wrong here?
A:
The documantation of IWorkbenchPart#getTitleToolTip() is quite specific:
Returns the title tool tip text of this workbench part. An empty string result indicates no tool tip. If this value changes the part must fire a property listener event with PROP_TITLE.
The tool tip text is used to populate the title bar of this part's visual container.
| {
"pile_set_name": "StackExchange"
} |
Q:
On load of jqgrid, apply default filter on loaded data
Grid having 3 options
1) My filters - Which are saved by me
2) Shared filters - which are shared by others
3) All - Both my and shared
I want to display grid with result default to my filters.
I have loaded all filters at once, By default it must show my filters records, but showing all filters records.
On selection of respective options mentioned above, grid loads data properly. Problem is only with default my filters
Please help me.
A:
I recommend you to upgrade old jqGrid 4.6 to the current version of free jqGrid. See here more details about the usage of free jqGrid. After the upgrade you can use the following options
datatype: "json",
loadonce: true,
forceClientSorting: true // force local sorting and filtering
search: true, // to apply the filter from postData.filters
postData: {
// the filters property is the filter, which need be applied
// to the data loaded from the server
filters: JSON.stringify({
groupOp: "OR",
rules: [
{ field: "shared_by", op: "eq", data: " " },
{ field: "shared_by", op: "eq", data: login_user_id }
]
})
},
...
the exact value of the postData.filters depends on the data saved on the server. As an example of usage see the demo https://jsfiddle.net/OlegKi/epcz4ptq/, created for the old answer. See another old answer for additional information.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to read in only numbers from a text file in C++
I am trying to read in the average rainfall for each month from a file that looks like this:
January 3.2 February 1.2 March 2.2
August 2.3 September 2.4
I need to take in the first 3 numbers and get the average of them along with output the 3rd month(March). I currently have this code:
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inputFile;
string name;
double num = 0, many = 0, total = 0, value = 0;
inputFile.open("Rainfall.txt");
for (int count = 1; count <= 6; count++)
{
inputFile >> name;
if (count == 1 || count == 3 || count == 5)
{
continue;
}
name += total;
cout << name << endl;
}
for (int inches = 1; inches <= 6; inches++)
{
inputFile >> name;
if (inches == 1 || inches == 3 || inches == 5)
{
continue;
}
cout << name << endl;
}
inputFile.close();
return 0;
}
And the output is looking like:
3.2
1.2
2.2
2.3
2.4
2.4
Now I can't add the first 3 numbers because they are strings and I need them to be doubles.
A:
If the format name number is consistent, you can read it in trivially:
std::string name;
double number = 0, total = 0;
while(inputFile >> name >> number)
{
cout << name << ' ' << number << '\n';
total += number;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Contextual shapes in margin calculation
I am having a doubt regarding margins in this project I am realizing. Should i consider these triangular shapes when calculating margins, or should I imagine a blank page as I am doing now? Sometimes I have the feeling the shape in the upper right corner comes too close to the text, or the page number in the bottom left; so I thought I could ask you opinion about it. Thank you!
A:
There's no steadfast rule here.
For me, things ultimately amount to visual perception. If the page "feels" cramped due to design elements, then factoring in the elements when considering margins will be beneficial. However if standard margins without considering design elements don't unnecessarily cause any visual "crowdedness" or confusion, then ignoring the elements in terms of layout is fine.
I don't think those particular elements encroach too far into the visual space and I think how the margins are configured and content is placed is fine in your sample.
Unrelated, I would consider reversing the angle of the blue and yellow elements though. As you have them, they convey a downward right movement, which psychologically conveys "melancholy" or "depression". Optimally you want an upward right movement to convey "joy" and "happiness". So, I would possible flop the angles, so the blue is upper left and the yellow is lower right. It is not impossible that it's this psychological impression you are picking up on which is making you uneasy with the layout.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# How to solve this dilema with optional arguments in method?
I have a db structure (Entity Framework Model) which looks something like that:
Business <-1----*-> Users <-*----0..1-> Role
Very simple and straightforward:
a business can have users.
a user must belong to a business.
a user may or may not relate to a role.
a role can relate to many users.
in the API level of the server I'd like to implement functionality that would allow the following method services:
//get all users
List<User> GetUsers();
//get all users belong to a business
List<User> GetUsers(int businessId);
//get all users with specific role
List<User> GetUsers(int roleId);
//get all users belong to a business with specific role
List<User> GetUsers(int businessId, int roleId);
But I do not wish to write 4 overloads to what I'd like to write in just a single method with optional parameters/named arguments, So
Instead of those 4 I'd like to create the following service method:
List<Users> GetUsers(
int?? businessId=undefined, int?? roleId=undefined)
{
var queryResult = new List<users>();
if(!businessId.IsUndefined)
queryResult= {get from db all business according to Id.}
if(!roleId.IsUndefined)
queryResult = queryResult.Where(item=>user.role.Id==roleId)
}
And now you wonder what's with the "??" thingy..
well, let's assume I want to get all users which has 0 relation to roles. - this would return a specific criteria.
now, let's assume I want to get all users regardless of role relation. - this would return a different criteria.
But named argument can be only Nullable to support that behavior:
List<Users> GetUsers(int? RoleId=null)
{
// is this null becuase it was not specified or is it null because
// it was called with null as argument.
// I need to know the difference to give the correct criteria.
// But I cannot tell the difference from within here...
// as in here it is simply null or some value.
}
So here comes a solution, I want an int to be not just nullable,
I also want it to be undefinable.. and I would be able to set a method as follows:
List<Users> GetUsers(int?? RoleId=undefined)
So an int?? would be to be any of those examples:
int?? x = undefined;
int?? x = null;
int?? x= 5;
The question is - is that possible?
Can I create somthing that would allow "int??" definition...
If so - how do I do that?
If not - how to overcome this problem?
A:
Maybe you could use wrapper classes for "business" and "role", but define implicit type conversions. These type conversions would allow your API users to send you either an int, or a Role.Undefined, or then null.
So the Role class for example would look something like this:
public class Role
{
private bool _isUndefined;
private int _val;
private Role()
{
_isUndefined = true;
}
private Role(int val)
{
_val = val;
}
public static Role Undefined
{
get { return new Role(); }
}
public static implicit operator Role(int val)
{
return new Role(val);
}
}
Then your signature would look like this:
List<User> GetUsers(Business business = null, Role role = null);
And your users could call it like:
GetUsers(Business.Undefined, Role.Undefined);
Or
GetUsers(1, 2);
Or
GetUsers(role: 8);
| {
"pile_set_name": "StackExchange"
} |
Q:
Log4j creating logs in multiple nodes. Want to create a single log in one node
I have a multi-node cluster Spark cluster. I am creating logs using log4j. Logs are getting created but one all the nodes in the cluster. They are also getting created in /tmp directory and not on any other directory. This is
spark2-submit --master yarn --deploy-mode cluster --files /path/log4j.properties --conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=log4j.properties" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=log4j.properties" --class com.dataLoad.Load_WF /path/LoadData.jar
How to append all the logs in one log file instead of multiple logs?
How to create logs in directory other than /tmp directory in Linux?
Sample code will be very helpful for understanding.
Much Appreciated.
A:
On a multinode spark cluster, the logs of your applications are written by the spark driver.
if you execute with client mode on node A, logs will be saved on node
A
if you execute with cluster mode, logs will be saved on node where
the spark driver is running.
We had the same problem, the solution we found is to use syslog to centralize the logs of each nodes, for all of our applications on the same node.
On the main node, you have to configure the syslog to be the logs server.
Inside /etc/syslog-ng/, you have to edit syslog-ng.conf to create destinations to save the centralized log files, :
example :
@version: 3.5
@include "scl.conf"
@include "`scl-root`/system/tty10.conf"
options {
time-reap(30);
mark-freq(10);
keep-hostname(yes);
};
source s_local { system(); internal(); };
source s_network {
syslog(transport(udp) port(514));
};
destination df_local2 {
file(
"/var/log/MyClusterLogs/myAppLogs.$YEAR-$MONTH-$DAY.log"
owner("user")
group("user")
perm(0777)
); };
filter f_local2 { facility(local2); };
log { source(s_network); filter(f_local2); destination(df_local2); };
And then, change the config in log4j.properties file of the spark application to point on syslog server :
log4j.rootCategory=INFO,FILE,SYSLOG
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.syslogHost=<syslog_server_ip>
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern=%d{ISO8601} %-5p [%t] %c{2} %x - %m%n
log4j.appender.SYSLOG.Facility=LOCAL2
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use custom templates in gii (using Yii 2)
I'm trying to find a way to use custom Gii templates for Yii 2, but looking at the missing documentation in the docs, I assume it's not possible yet?
Or am I missing something?
A:
Copy ie. the crud generator templates from gii/generators/crud/templates to your application app/templates/mycrud.
Then define the templates in your config:
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
'generators' => [
'crud' => [
'class' => 'yii\gii\generators\crud\Generator',
'templates' => ['mycrud' => '@app/templates/mycrud']
]
]
];
Until the documentation is finished you may also have a look at my Gii extension how to create a custom generator and templates.
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaScript Strange Array Definition Syntax
A few coworkers and I have come across some more strange JavaScript syntax. We are having trouble explaining the following behaviour (I am using the Chrome console):
> {}[1]
Yields
[1]
Essentially, it is valid syntax to include any object (not just empty) before the array, and the result is always just the array. Is there any explanation for this? Any case where this doesn't behave this way?
Also, this question is sort of hard to search for, since it consists of characters that don't play well with search engines. Please let me know if this is a duplicate question.
A:
{} is an empty code block statement. It's followed by an Array literal [1], which is the value that your program {}[1] evaluates to.
it's pretty much equivalent to:
if (true) {
// empty block!
}
[1];
If you wanted to get the value with key 1 in an empty object literal, use parentheses:
({})[1] // undefined
You can use AST Explorer to see the JavaScript parser's view of your code.
A:
A block statement (or compound statement in other languages) is used
to group zero or more statements. The block is delimited by a pair of
curly brackets.
{} <-- block statement
[1] <-- array
so basically typed > [1]
| {
"pile_set_name": "StackExchange"
} |
Q:
Limit duplicate queries in Laravel
I only need the latest 5 rows in my query so I use
$view->with('recent', Transaction::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
This gives me what I need in my view, but the DeBug Bar states:
14 statements were executed, 14 of which were duplicated
I currently have 14 records in that table. The more records I add in the table the more duplicates I get.
How can I cut down on those queries?
Currently calling it like this:
@foreach($recent as $rec)
<li>{{ number_format($rec->amount / 100, 2) }}</li>
@endforeach
A:
try this
change 'change.to.footer' to your footer.blade.php path
change \App\Transaction to your model path
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
view()->composer('change.to.footer', function ($view) {
$view->with('recent', \App\Transaction::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
if you want use the variable in all blade,
may be you can make a model method
// Transaction model
public static function recent()
{
return static::SELECT('amount')
->latest()
->where('amount', '!=', null)
->take(5)->get());
}
make a view composer
public function boot()
{
view()->share('recent', \App\Transaction::recent());
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why are there N's after Sanger sequencing?
After sending a DNA sample for sequencing, the resulting sequence had N's in the beginning and end of the sequence. I know the N's mean that the computer can't tell what the base pair is, but why is this?
A:
Typically Sanger sequencing will run into a few errors. Sometimes the traces will overlap as below in red and the computer will call N. If you truly wanted to figure out the correct basepair, you can look at the trace.
A:
As you accurately stated, N bases in sequence data generally means the software is unable to identify the base. N bases may appear at the beginning of the sequence result for a number of reasons. One reason would be purification of the amplified product before electrophoresis. Salts in the sample or a poor purification could leave excess dyes in the sample and appear as "dye blobs." Another reason is the software may have started analysis too soon before accurate sequence begins. Typically, quality sequence data begins 30 bases from the primer. N bases at end of the sequence simply could be the end of sequence data as stated earlier. Other reasons include hairpin loops and poly base regions that cause early termination. The best way to determine the cause is to look at the trace data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error handling with try/catch or eval while opening file in perl
I have written simple code snippets, to handle an error occurring while opening the file in restricted(where we need root permission)
following code works fine and gives an error as o/p
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny;
my $file_name = "/var/log/test.txt"; # needs root permission to create file
if(open(HAN, ">$file_name")){
print "sucuessfully opened file \n ";
} else {
print "Error with if/else while openning file : $! \n";
}
o/p:
Error with if/else while opening file : Permission denied
when i use try/catch or eval with same code and opens file
try {
open(HAN, ">$file_name");
} catch {
print "Error with try/catch while opening file : $_ \n";
};
or
eval {
open(HAN, ">$file_name");
};
print " Error with eval while opening file : $@ \n";
it shows no output in $_ or $@, why this is happing?
A:
open does not throw an exception if it fails, it returns a false value and the error is stored in $!. Typical usage is therefore
open my $fh, '>', $filename or die "Couldn't open '$filename' for writing: $!";
If you have a lot of I/O code, or other things that might throw exceptions, you might prefer than open (and other I/O functions) automatically throw an error on failure. You can do this with autodie:
use autodie qw(:io);
As @sputnick mentions, you should use warnings; in addition to use strict;
Finally, here is an example of catching a I/O exception only:
use warnings;
use strict;
use autodie qw(:io);
use Try::Tiny;
try {
open my $fh, '>', $filename;
... more code ...
}
catch {
if ($_->isa('autodie::exception') && $_->matches(':io')) {
print "Error doing something with '$filename': $_\n";
}
else {
die $_; # rethrow
}
};
On Perl 5.10+, you can use given and when instead of this verbose code; see the autodie docs for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
How To get the value from a Json response
My json resposnse from webservice is like
{"d":"[{\"userid\":507}]"} in Android. I need to get the userid from this response. How is it possible?
A:
At last i got the exact answer for my solution . I got the userid from my response using this code`
result=(String) jobj.getString("d");
JSONArray arr = new JSONArray(result);
JSONObject js=arr.getJSONObject(0);
String userid=js.getString("Userid");`
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.