For quick reference along with clear concise examples, Allen Holub's UML Quick Reference is excellent:
http://www.holub.com/goodies/uml/
(There are quite a few specific examples of arrows and pointers in the first column of a table, with descriptions in the second column.)
Whoever wants UML deserves Rational Rose :)
I think this link will do your homework: http://ootips.org/uml-hasa.html
To understand the terms I remember an example in my early programming days:
If you have a 'chess board' object that contains 'box' objects that is composition because if the 'chess board' is deleted there is no reason for the boxes to exist anymore.
If you have a 'square' object that have a 'color' object and the square gets deleted the 'color' object may still exist, that is aggregation
Both of them are associations, the main difference is conceptual
Typically you model the enum itself as a class with the enum
stereotype
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.
UPDATE Oct 11th, 2013
My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.
I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.
The Answer (Oct 11th, 2013)
Tools
Steps
Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml
Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.
ALT+W -> show view -> papyrus -> model explorer
In that view, you'll find your classes like in the picture
In the view Right click root model -> New diagram
Then start grabbing classes to the diagram from the view
Some features
To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!
You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram
one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All
Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc
After all of that your settings will show diagrams like
Synchronization isn't available as far as I know you'll need to manually import any new classes.
That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.
Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.
An object associated with a composition relationship will not exist outside the containing object. Examples are an Appointment and the owner (a Person) or a Calendar; a TestResult and a Patient.
On the other hand, an object that is aggregated by a containing object can exist outside that containing object. Examples are a Door and a House; an Employee and a Department.
A dependency relates to collaboration or delegation, where an object requests services from another object and is therefor dependent on that object. As the client of the service, you want the service interface to remain constant, even if future services are offered.
The TopCoder UML Tool is a very good free UML tool.
Very simple , using Alt fragment
Lets take an example of sequence diagram for an ATM machine.Let's say here you want
IF card inserted is valid then prompt "Enter Pin"....ELSE prompt "Invalid Pin"
Then here is the sequence diagram for the same
Hope this helps!
You can install one of the free pugins - Code Iris.
Other tools of this type in the IntelliJ IDEA are paid.
I hope it will help you.
This may be contentious but the “includes are always and extends are sometimes” is a very common misconception which has almost taken over now as the de-facto meaning. Here’s a correct approach (in my view, and checked against Jacobson, Fowler, Larmen and 10 other references).
The key to Include and extend use case relationships is to realize that, common with the rest of UML, the dotted arrow between use cases is a dependency relationship. I’ll use the terms ‘base’, ‘included’ and ‘extending’ to refer to the use case roles.
A base use case is dependent on the included use case(s); without it/them the base use case is incomplete as the included use case(s) represent sub-sequences of the interaction that may happen always OR sometimes. (This is contrary to a popular misconception about this, what your use case suggests always happens in the main scenario and sometimes happens in alternate flows simply depends on what you choose as your main scenario; use cases can easily be restructured to represent a different flow as the main scenario and this should not matter).
In the best practice of one way dependency the base use case knows about (and refers to) the included use case, but the included use case shouldn’t ‘know’ about the base use case. This is why included use cases can be: a) base use cases in their own right and b) shared by a number of base use cases.
The extending use case is dependent on the base use case; it literally extends the behavior described by the base use case. The base use case should be a fully functional use case in its own right (‘include’s included of course) without the extending use case’s additional functionality.
Extending use cases can be used in several situations:
One important aspect to consider is that the extending use case can ‘insert’ behavior in several places in the base use case’s flow, not just in a single place as an included use case does. For this reason, it is highly unlikely that an extending use case will be suitable to extend more than one base use case.
As to dependency, the extending use case is dependent on the base use case and is again a one-way dependency, i.e. the base use case doesn’t need any reference to the extending use case in the sequence. That doesn’t mean you can’t demonstrate the extension points or add a x-ref to the extending use case elsewhere in the template, but the base use case must be able to work without the extending use case.
I hope I’ve shown that the common misconception of “includes are always, extends are sometimes” is either wrong or at best simplistic. This version actually makes more sense if you consider all the issues about the directionality of the arrows the misconception presents – in the correct model it’s just dependency and doesn’t potentially change if you refactor the use case contents.
Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.
If you are looking for UML sequence diagrams, try searching for UML Sequence in the search box and add them.
You can either browse through My shapes to access them. They will be available in the in the sidebar nevertheless once you search.
Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern
As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.
jz
vipera is a small application designer, and uml is included. You can see it in:
Best regards.
There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.
Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.
I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).
This simple solution forces the IEnumerable
's generic type to implement IComparable
. Because of
OrderBy
's definition.
If you don't want to make such an assumption but still want use this solution, you can use the following piece of code :
bool equal = collection1.OrderBy(i => i?.GetHashCode())
.SequenceEqual(collection2.OrderBy(i => i?.GetHashCode()));
select UTF-8 enconding when importing. if you use Office 2007 this is where you chose it : right after you open the file.
That's the platform toolset for VS2015. You uninstalled it, therefore it is no longer available.
To change your Platform Toolset:
Control Panel -> System -> Advanced system settings -> Environment Variables
I changed JAVA_HOME to JAVA and again changed JAVA to JAVA_HOME.
and Its working fine.
JavaScript does require semicolons, it's just that the interpreter will insert them for you on line breaks where possible*.
Unfortunately, the code
var a = new B(args)(stuff)()
does not result in a syntax error, so no ;
will be inserted. (An example which can run is
var answer = new Function("x", "return x")(function(){return 42;})();
To avoid surprises like this, train yourself to always end a statement with ;
.
@AlexDuggleby: you don't need to copy the worksheets, you can save them directly. e.g.:
Public Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
SaveToDirectory = "C:\"
For Each WS In ThisWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
End Sub
Only potential problem is that that leaves your workbook saved as the last csv file. If you need to keep the original workbook you will need to SaveAs it.
There are so many ways:
Luckily git stash pop
does not change the stash in the case of a conflict!
So nothing, to worry about, just clean up your code and try it again.
Say your codebase was clean before, you could go back to that state with: git checkout -f
Then do the stuff you forgot, e.g. git merge missing-branch
After that just fire git stash pop
again and you get the same stash, that conflicted before.
Keep in mind: The stash is safe, however, uncommitted changes in the working directory are of course not. They can get messed up.
Thinking about it in general, I would strongly consider hiding coordinate system behind well-designed abstraction. Quoting Uncle Bob and his book:
class Point(object)
def setCartesian(self, x, y)
def setPolar(self, rho, theta)
def getX(self)
def getY(self)
def getRho(self)
def setTheta(self)
With interface like that any user of Point class may choose convenient representation, no explicit conversions will be performed. All this ugly sines, cosines etc. will be hidden in one place. Point class. Only place where you should care which representation is used in computer memory.
Of all the suggestions, nobdy used the razor syntax (this is with bootstrap styles as well). This will make a button that redirects to the Login view in the Account controller:
<form>
<button class="btn btn-primary" asp-action="Login" asp-
controller="Account">@Localizer["Login"]</button>
</form>
You are able to do this using Java 8 stream APIs. The following code creates the string "cccc"
from "c"
:
String s = "c";
int n = 4;
String sRepeated = IntStream.range(0, n).mapToObj(i -> s).collect(Collectors.joining(""));
To print your context ,you can write code like this :
FILE *fp;
char *of;
sprintf(of,"%s%s",text1,text2);
fp=fopen(of,'w');
fprintf(fp,"your print line");
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder
and selected file name
you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;
, that means in the OpenFileDialog()
you are able to select multiple files (by pressing ctrl
key and left mouse click for selection).
In that case you could get all selected files in string[]
:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true
this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
You can convert your RDD
to a DataFrame
then show()
it.
// For implicit conversion from RDD to DataFrame
import spark.implicits._
fruits = sc.parallelize([("apple", 1), ("banana", 2), ("orange", 17)])
// convert to DF then show it
fruits.toDF().show()
This will show the top 20 lines of your data, so the size of your data should not be an issue.
+------+---+
| _1| _2|
+------+---+
| apple| 1|
|banana| 2|
|orange| 17|
+------+---+
var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
});
console.log(isValid);
theString.substring(theString.length() - 2)
As others said, Stopwatch
should be the right tool for this. There can be few improvements made to it though, see this thread specifically: Benchmarking small code samples in C#, can this implementation be improved?.
I have seen some useful tips by Thomas Maierhofer here
Basically his code looks like:
//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;
//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);
//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;
//warm up
method();
var stopwatch = new Stopwatch()
for (int i = 0; i < repetitions; i++)
{
stopwatch.Reset();
stopwatch.Start();
for (int j = 0; j < iterations; j++)
method();
stopwatch.Stop();
print stopwatch.Elapsed.TotalMilliseconds;
}
Another approach is to rely on Process.TotalProcessTime
to measure how long the CPU has been kept busy running the very code/process, as shown here This can reflect more real scenario since no other process affects the measurement. It does something like:
var start = Process.GetCurrentProcess().TotalProcessorTime;
method();
var stop = Process.GetCurrentProcess().TotalProcessorTime;
print (end - begin).TotalMilliseconds;
A naked, detailed implementation of the samething can be found here.
I wrote a helper class to perform both in an easy to use manner:
public class Clock
{
interface IStopwatch
{
bool IsRunning { get; }
TimeSpan Elapsed { get; }
void Start();
void Stop();
void Reset();
}
class TimeWatch : IStopwatch
{
Stopwatch stopwatch = new Stopwatch();
public TimeSpan Elapsed
{
get { return stopwatch.Elapsed; }
}
public bool IsRunning
{
get { return stopwatch.IsRunning; }
}
public TimeWatch()
{
if (!Stopwatch.IsHighResolution)
throw new NotSupportedException("Your hardware doesn't support high resolution counter");
//prevent the JIT Compiler from optimizing Fkt calls away
long seed = Environment.TickCount;
//use the second Core/Processor for the test
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(2);
//prevent "Normal" Processes from interrupting Threads
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
//prevent "Normal" Threads from interrupting this thread
Thread.CurrentThread.Priority = ThreadPriority.Highest;
}
public void Start()
{
stopwatch.Start();
}
public void Stop()
{
stopwatch.Stop();
}
public void Reset()
{
stopwatch.Reset();
}
}
class CpuWatch : IStopwatch
{
TimeSpan startTime;
TimeSpan endTime;
bool isRunning;
public TimeSpan Elapsed
{
get
{
if (IsRunning)
throw new NotImplementedException("Getting elapsed span while watch is running is not implemented");
return endTime - startTime;
}
}
public bool IsRunning
{
get { return isRunning; }
}
public void Start()
{
startTime = Process.GetCurrentProcess().TotalProcessorTime;
isRunning = true;
}
public void Stop()
{
endTime = Process.GetCurrentProcess().TotalProcessorTime;
isRunning = false;
}
public void Reset()
{
startTime = TimeSpan.Zero;
endTime = TimeSpan.Zero;
}
}
public static void BenchmarkTime(Action action, int iterations = 10000)
{
Benchmark<TimeWatch>(action, iterations);
}
static void Benchmark<T>(Action action, int iterations) where T : IStopwatch, new()
{
//clean Garbage
GC.Collect();
//wait for the finalizer queue to empty
GC.WaitForPendingFinalizers();
//clean Garbage
GC.Collect();
//warm up
action();
var stopwatch = new T();
var timings = new double[5];
for (int i = 0; i < timings.Length; i++)
{
stopwatch.Reset();
stopwatch.Start();
for (int j = 0; j < iterations; j++)
action();
stopwatch.Stop();
timings[i] = stopwatch.Elapsed.TotalMilliseconds;
print timings[i];
}
print "normalized mean: " + timings.NormalizedMean().ToString();
}
public static void BenchmarkCpu(Action action, int iterations = 10000)
{
Benchmark<CpuWatch>(action, iterations);
}
}
Just call
Clock.BenchmarkTime(() =>
{
//code
}, 10000000);
or
Clock.BenchmarkCpu(() =>
{
//code
}, 10000000);
The last part of the Clock
is the tricky part. If you want to display the final timing, its up to you to choose what sort of timing you want. I wrote an extension method NormalizedMean
which gives you the mean of the read timings discarding the noise. I mean I calculate the the deviation of each timing from the actual mean, and then I discard the values which was farer (only the slower ones) from the mean of deviation (called absolute deviation; note that its not the often heard standard deviation), and finally return the mean of remaining values. This means, for instance, if timed values are { 1, 2, 3, 2, 100 }
(in ms or whatever), it discards 100
, and returns the mean of { 1, 2, 3, 2 }
which is 2
. Or if timings are { 240, 220, 200, 220, 220, 270 }
, it discards 270
, and returns the mean of { 240, 220, 200, 220, 220 }
which is 220
.
public static double NormalizedMean(this ICollection<double> values)
{
if (values.Count == 0)
return double.NaN;
var deviations = values.Deviations().ToArray();
var meanDeviation = deviations.Sum(t => Math.Abs(t.Item2)) / values.Count;
return deviations.Where(t => t.Item2 > 0 || Math.Abs(t.Item2) <= meanDeviation).Average(t => t.Item1);
}
public static IEnumerable<Tuple<double, double>> Deviations(this ICollection<double> values)
{
if (values.Count == 0)
yield break;
var avg = values.Average();
foreach (var d in values)
yield return Tuple.Create(d, avg - d);
}
I had the same problem and I rename the "repository" folder on ".m2" (something like repositoryBkp the name is not important is just in case something goes wrong) and create a new "repository" folder, then I re run maven and all the project compile successfully
var str = "Text\",\"Text\",\"Text";
var newstr = str.Replace("\",\"", ";");
If you don't know how many columns you are going to have, the declaration
table-layout: fixed
along with not setting any column widths, would imply that browsers divide the total width evenly - no matter what.
That can also be the problem with this approach, if you use this, you should also consider how overflow is to be handled.
How do I have to do in Python for calling an static method from another static method of the same class?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
figlegend may be what you're looking for: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend
Example here: http://matplotlib.org/examples/pylab_examples/figlegend_demo.html
Another example:
plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )
or:
fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )
I just want to add something here: changing the title via JavaScript is actually useful if you're updating a database via AJAX, so then the title changes without you having to refresh the page. The title actually changes via your server side scripting language, but having it change via JavaScript is just a usability and UI thing that makes the user experience more enjoyable and fluid.
Now, if you're changing the title via JavaScript just for the hell of it, then you should not be doing that.
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
SSLHandshakeException can be resolved 2 ways.
Incorporating SSL
Get the SSL (by asking the source system administrator, can also be downloaded by openssl command, or any browsers downloads the certificates)
Add the certificate into truststore (cacerts) located at JRE/lib/security
provide the truststore location in vm arguments as "-Djavax.net.ssl.trustStore="
Ignoring SSL
For this #2, please visit my other answer on another stackoverflow website: How to ingore SSL verification Ignore SSL Certificate Errors with Java
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success
C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>
We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan
Don't use array_values
on your $row
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, $row);
}
Also, the preferred way to add a value to an array is writing $array[] = $value;
, not using array_push
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC)
but to use mysql_fetch_assoc($result)
directly.
$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
{
$res_arr_values[] = $row;
}
If you don't extend JFrame
and use JFrame
itself in variable, you can use:
frame.dispose();
System.exit(0);
@Thad you need to add a blur event handler as well
$(document).ready(function(){
$("#dropdown").mousedown(function(){
if($.browser.msie) {
$(this).css("width","auto");
}
});
$("#dropdown").change(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
$("#dropdown").blur(function(){
if ($.browser.msie) {
$(this).css("width","175px");
}
});
});
However, this will still expand the selectbox on click, instead of just the elements. (and it seems to fail in IE6, but works perfectly in Chrome and IE7)
It might be that the package "Combinations" is not updated anymore and does not work with a recent version of R (I was also unable to install it on R 2.13.1 on windows). The package "combinat" installs without problem for me and might be a solution for you depending on what exactly you're trying to do.
You can use the replace
function
UPDATE your_table SET field = REPLACE(your_field, 'cat','dog')
The function definition is as follows (got from here):
replace(string text, from text, to text)
and returns the modified text. You can also check out this sql fiddle.
try this!!!
using following code you could compare one or many fields to generate a result list as per your need. result list will contain only modified item(s).
// veriables been used
List<T> diffList = new List<T>();
List<T> gotResultList = new List<T>();
// compare First field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField1 == a.MyListTField1))).ToList();
// Generate result list
diffList.AddRange(gotResultList);
// compare Second field within my MyList
gotResultList = MyList1.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2)).ToList().Except(gotResultList.Where(a => !MyList2.Any(a1 => a1.MyListTField2 == a.MyListTField2))).ToList();
// Generate result list
diffList.AddRange(gotResultList);
MessageBox.Show(diffList.Count.ToString);
From application perspective, if one needs only to avoid duplicates then HashSet
is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet
has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.
In Visual Studio 2019, this can also be configured in Tools -> Options -> General -> View whitespace
There is also str_sub
from the stringr package
x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"
for line in file('/tmp/foo'):
print line.strip('\n')
char* myFunction()
{
return "My String";
}
In C, string literals are arrays with the static constant memory class, so returning a pointer to this array is safe. More details are in Stack Overflow question "Life-time" of a string literal in C
LocalDate // Represent a date-only, without time-of-day and without time zone.
.now() // Better to pass a `ZoneId` optional argument to `now` as shown below than rely implicitly on the JVM’s current default time zone.
.getDayOfMonth() // Interrogate for the day of the month (1-31).
The modern approach is the LocalDate
class to represent a date-only value.
A time zone is crucial in determine the current date. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
int dayOfMonth = ld.getDayOfMonth();
You can also get the day-of-week.
DayOfWeek dow = ld.getDayOfWeek();
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
UPDATE: The Joda-Time project is now in maintenance mode, and advises migration to the java.time classes. This section left intact for history.
Using the Joda-Time 2.5 library rather than the notoriously troublesome java.util.Date and .Calendar classes.
Time zone is crucial to determining a date. Better to specify the zone rather than rely implicitly on the JVM’s current default time zone being assigned.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone ).withTimeAtStartOfDay();
int dayOfMonth = now.getDayOfMonth();
Or use similar code with the LocalDate
class that has no time-of-day portion.
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter
property.
EDIT: Formatting.
d = <dict>
values = d.values()
Java doesn't have an analog to C++'s structs, but you can use classes with all public members.
My text marquee for more text, and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
with pages as (
SELECT object_id, SUM (reserved_page_count) as reserved_pages, SUM (used_page_count) as used_pages,
SUM (case
when (index_id < 2) then (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
else lob_used_page_count + row_overflow_used_page_count
end) as pages
FROM sys.dm_db_partition_stats
group by object_id
), extra as (
SELECT p.object_id, sum(reserved_page_count) as reserved_pages, sum(used_page_count) as used_pages
FROM sys.dm_db_partition_stats p, sys.internal_tables it
WHERE it.internal_type IN (202,204,211,212,213,214,215,216) AND p.object_id = it.object_id
group by p.object_id
)
SELECT object_schema_name(p.object_id) + '.' + object_name(p.object_id) as TableName, (p.reserved_pages + isnull(e.reserved_pages, 0)) * 8 as reserved_kb,
pages * 8 as data_kb,
(CASE WHEN p.used_pages + isnull(e.used_pages, 0) > pages THEN (p.used_pages + isnull(e.used_pages, 0) - pages) ELSE 0 END) * 8 as index_kb,
(CASE WHEN p.reserved_pages + isnull(e.reserved_pages, 0) > p.used_pages + isnull(e.used_pages, 0) THEN (p.reserved_pages + isnull(e.reserved_pages, 0) - p.used_pages + isnull(e.used_pages, 0)) else 0 end) * 8 as unused_kb
from pages p
left outer join extra e on p.object_id = e.object_id
Takes into account internal tables, such as those used for XML storage.
Edit: If you divide the data_kb
and index_kb
values by 1024.0, you will get the numbers you see in the GUI.
For everyone coming to this thread with fractional seconds in your timestamp use:
to_timestamp('2018-11-03 12:35:20.419000', 'YYYY-MM-DD HH24:MI:SS.FF')
I don't know which promise library you are using, but most have something like allSettled.
Edit: Ok since you want to use plain ES6 without external libraries, there is no such method.
In other words: You have to loop over your promises manually and resolve a new combined promise as soon as all promises are settled.
In JavaScript this will translate to an object that with data might look like this
Interfaces in TypeScript are a dev time construct (purely for tooling ... 0 runtime impact). You should write the same TypeScript as your JavaScript.
Contrary to some answers posted in this thread, adding 'DIRS': ['templates']
has no effect(it's redundant) since templates
is the default path where Django looks for templates.
If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS
in the main project settings.py
.
INSTALLED_APPS': [
# ...
'my_app',
]
Quoting Django's Templates documentation:
class DjangoTemplates¶
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
When you create an application to your project, there's no templates
directory inside the application directory. Since that you can have an application without using templates, Django doesn't create such directory. That is, you have to create it and storing your templates in there.
Here's another paragraph from Django Tutorial documentation, which is even clearer:
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
This is so common but so profoundly wrong. Protobuf data is not string data. It certainly isn't ASCII. You are using the encoding backwards. A text encoding transfers:
You do not have "formatted bytes". You have arbitrary bytes. You need to use something like a base-n (commonly: base-64) encode. This transfers
look at Convert.ToBase64String and Convert. FromBase64String
If your RDBMS supports the OVER clause...
SELECT
title
FROM
(
select
title, count(*) OVER (PARTITION BY title) as cnt
from
kmovies
) T
ORDER BY
cnt DESC
drop procedure if exists doWhile;
DELIMITER //
CREATE PROCEDURE doWhile()
BEGIN
DECLARE i INT DEFAULT 2376921001;
WHILE (i <= 237692200) DO
INSERT INTO `mytable` (code, active, total) values (i, 1, 1);
SET i = i+1;
END WHILE;
END;
//
CALL doWhile();
A Third Answer
Sorry, maybe I have it correct this time...
var savedBox1, savedBox2, state1=0, state2=0;
jQuery(document).ready(function() {
jQuery(".rec1").click(function() {
if (state1==0){
savedBox1 = jQuery('#rec-box').html();
jQuery('#rec-box').html(jQuery(this).next().html());
state1 = 1;
}else{
jQuery('#rec-box').html(savedBox1);
state1 = 0;
}
});
jQuery(".rec2").click(function() {
if (state1==0){
savedBox2 = jQuery('#rec-box2').html();
jQuery('#rec-box2').html(jQuery(this).next().html());
state2 = 1;
}else{
jQuery('#rec-box2').html(savedBox2);
state2 = 0;
}
});
});
Is required that you have a form?
If not, then you could use this:
<div>
<input type="hidden" value="ServletParameter" />
<input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>
with the following JavaScript:
function callJavaScriptServlet() {
this.form.action = "MyServlet";
this.form.submit();
}
find supports wildcard matches, just add a *
:
find / -type d -name "ora10*"
As an extension method:
public static class Extensions
{
public static string AsString(this XmlDocument xmlDoc)
{
using (StringWriter sw = new StringWriter())
{
using (XmlTextWriter tx = new XmlTextWriter(sw))
{
xmlDoc.WriteTo(tx);
string strXmlText = sw.ToString();
return strXmlText;
}
}
}
}
Now to use simply:
yourXmlDoc.AsString()
Maybe it is little bit of an extreme, but I am using this super short version:
curl -svo. <URL>
Explanation:
-v
print debug information (which does include headers)
-o.
send web page data (which we want to ignore) to a certain file, .
in this case, which is a directory and is an invalid destination and makes the output to be ignored.
-s
no progress bar, no error information (otherwise you would see Warning: Failed to create the file .: Is a directory
)
warning: result always fails (in terms of error code, if reachable or not). Do not use in, say, conditional statements in shell scripting...
I suggest you to take a look into SharpGrabber - a .NET Standard library I've written just for this purpose. It is newer than YouTubeExtractor and libvideo.
It supports YouTube
and Instagram
as the time of this answer. This project also offers high-quality video and audio muxing and a cross-platform desktop application.
This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.
cPickle
comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle
, you can do this:
>>> import _pickle as cPickle
However, in 3.x, it's easier just to use pickle
.
No need to install anything. If something requires cPickle
in python 3.x, then that's probably a bug.
__all__
is very good - it helps guide import statements without automatically importing modules
http://docs.python.org/tutorial/modules.html#importing-from-a-package
using __all__
and import *
is redundant, only __all__
is needed
I think one of the most powerful reasons to use import *
in an __init__.py
to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py
files empty.
for example:
foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo
then the app grows and now it's a whole folder
foo/
__init__.py
foofactories.py
tallFoos.py
shortfoos.py
mediumfoos.py
santaslittlehelperfoo.py
superawsomefoo.py
anotherfoo.py
then the init script can say
__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo
so that a script written to do the following does not break during the change:
from foo import fooFactory, tallFoo, shortFoo
take look at my solution
i want to make visaCard-note
div to be visible only if selected cardType
is visa
and here is the html
<select name="cardType">
<option value="1">visa</option>
<option value="2">mastercard</option>
</select>
here is the js
var visa="1";//visa is selected by default
$("select[name=cardType]").change(function () {
document.getElementById('visaCard-note').style.visibility = this.value==visa ? 'visible' : 'hidden';
})
Swift 5 answer based on @ZpaceZombor's excellent answer
If you have a UIImage, just use
var image: UIImage = ....
image.draw(in: CGRect)
If you have a CGImage use my category below
Note: Unlike some other answers, this one takes into account that the rect you want to draw in might have y != 0. Those answers that don't take that into account are incorrect and won't work in the general case.
extension CGContext {
final func drawImage(image: CGImage, inRect rect: CGRect) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
translateBy(x: 0, y: ty)
scaleBy(x: 1.0, y: -1.0)
//draw image
let rect__y_zero = CGRect(x: rect.origin.x, y: 0, width: rect.width, height: rect.height)
draw(image, in: rect__y_zero)
//flip back
scaleBy(x: 1.0, y: -1.0)
translateBy(x: 0, y: -ty)
}
}
Use like this:
let imageFrame: CGRect = ...
let context: CGContext = ....
let img: CGImage = .....
context.drawImage(image: img, inRect: imageFrame)
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
$("input[placeholder]").focusin(function () {
$(this).data('place-holder-text', $(this).attr('placeholder')).attr('placeholder', '');
})
.focusout(function () {
$(this).attr('placeholder', $(this).data('place-holder-text'));
});
You can try this
markers[markers.length-1].setMap(null);
Hope it works.
I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.
map
is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)
noremap
is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map
. (Think of the nore
prefix to mean "non-recursive".)
(Note that there are also the !
modes like map!
that apply to insert & command-line.)
See below for what "recursive" means in this context.
Prepending a mode letter like n
modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map
wouldn't apply to (e.g. "insert").
Use help map-modes
will show you a few tables that explain how to control which modes the mapping applies to.
Mode letters:
n
: normal onlyv
: visual and selecto
: operator-pendingx
: visual onlys
: select onlyi
: insertc
: command-linel
: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.
The expansion stops when one of these is true:
At that point, Vim's default "meaning" of the final result is applied/executed.
"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.
Example:
nmap K H
nnoremap H G
nnoremap G gg
The above causes K
to expand to H
, then H
to expand to G
and stop. It stops because of the nnoremap
, which expands and stops immediately. The meaning of G
will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).
The mapping of G
to gg
only applies if you press G
, but not if you press K
. This mapping doesn't affect pressing K
regardless of whether G
was mapped recursively or not, since it's line 2 that causes the expansion of K
to stop, so line 3 wouldn't be used.
You can easily launch a market link or an install prompt:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);
However, you cannot install .apks without user's explicit permission; not unless the device and your program is rooted.
<div class="fb_share">
<a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
href="http://www.facebook.com/sharer.php">Partilhar</a>
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php } }
add_action('thesis_hook_byline_item','fb_share');
The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:
set rowcount @top
select * from sometable
set rowcount 0
Hope this helps
Oisin.
(edited to replace @@rowcount with rowcount - thanks augustlights)
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
rm file3.txt
cat file1.out | while read line1
do
cat file2.out | while read line2
do
if [[ $line1 == $line2 ]]; then
echo $line1 >>file3.out
fi
done
done
This should do it.
vim editor + g++ compiler(GNU C++) + gdb - might help you
The top answer by @808sound did not work for me. I wanted to resize
So instead I opened up Inkscape, then went to File
, Export as PNG file
and a GUI box popped up that allowed me to set the exact dimensions I needed.
Version on Ubuntu 16.04 Linux
:
Inkscape 0.91 (September 2016)
(This image is from Kenney.nl's asset packs by the way)
Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.
<?php
function getSSLPage($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSLVERSION,3);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>
When you set the SSL Version with curl to v3 then it works.
Edit:
Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.
http://curl.haxx.se/docs/caextract.html
here you can download the root certificates.
curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
Then you can use the CURLOPT_SSL_VERIFYPEER
option with true
otherwise you get an error.
There are a bunch of similar questions about this, so I'll post what I wrote before:
The only way I got this to work on my machine was to do it this way:
# Ignore all directories, and all sub-directories, and it's contents:
*/*
#Now ignore all files in the current directory
#(This fails to ignore files without a ".", for example
#'file.txt' works, but
#'file' doesn't):
*.*
#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*
Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.
This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153
These were useful topics:
I also tried
*
*/*
**/**
and **/wp-content/themes/**
or /wp-content/themes/**/*
None of that worked for me, either. Lots of trial and error!
You can use a custom style:
<!-- Alert Dialog -->
<style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
<!-- Background Color-->
<item name="android:background">@color/.....</item>
<!-- Text Color for title and message -->
<item name="colorOnSurface">@color/......</item>
<!-- Style for positive button -->
<item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<!-- Style for negative button -->
<item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
</style>
<style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
<!-- text color for the button -->
<item name="android:textColor">@color/.....</item>
<!-- Background tint for the button -->
<item name="backgroundTint">@color/primaryDarkColor</item>
</style>
And just use the default MaterialAlertDialogBuilder
:
new MaterialAlertDialogBuilder(AlertDialogActivity.this,
R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
.setTitle("Dialog")
.setMessage("Message... ....")
.setPositiveButton("Ok", /* listener = */ null)
.show();
Here is an actual working version of the above async foreach variants with sequential processing:
public static async Task ForEachAsync<T>(this List<T> enumerable, Action<T> action)
{
foreach (var item in enumerable)
await Task.Run(() => { action(item); }).ConfigureAwait(false);
}
Here is the implementation:
public async void SequentialAsync()
{
var list = new List<Action>();
Action action1 = () => {
//do stuff 1
};
Action action2 = () => {
//do stuff 2
};
list.Add(action1);
list.Add(action2);
await list.ForEachAsync();
}
What's the key difference? .ConfigureAwait(false);
which keeps the context of main thread while async sequential processing of each task.
You could use the Chr(int) function
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
use session_start()
at the top of the page.
for more details please read the link session_start
The ability to read an NFC tag has been added to iOS 11 which only support iPhone 7 and 7 plus
As a test drive I made this repo
First: We need to initiate NFCNDEFReaderSession class
var session: NFCNDEFReaderSession?
session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
Then we need to start the session by:
session?.begin()
and when done:
session?.invalidate()
The delegate (which self should implement) has basically two functions:
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage])
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error)
here is my reference Apple docs
Answer to the question is : There are different way to print stderr in python but that depends on 1.) which python version we are using 2.) what exact output we want.
The differnce between print and stderr's write function: stderr : stderr (standard error) is pipe that is built into every UNIX/Linux system, when your program crashes and prints out debugging information (like a traceback in Python), it goes to the stderr pipe.
print: print is a wrapper that formats the inputs (the input is the space between argument and the newline at the end) and it then calls the write function of a given object, the given object by default is sys.stdout, but we can pass a file i.e we can print the input in a file also.
Python2: If we are using python2 then
>>> import sys
>>> print "hi"
hi
>>> print("hi")
hi
>>> print >> sys.stderr.write("hi")
hi
Python2 trailing comma has in Python3 become a parameter, so if we use trailing commas to avoid the newline after a print, this will in Python3 look like print('Text to print', end=' ') which is a syntax error under Python2.
http://python3porting.com/noconv.html
If we check same above sceario in python3:
>>> import sys
>>> print("hi")
hi
Under Python 2.6 there is a future import to make print into a function. So to avoid any syntax errors and other differences we should start any file where we use print() with from future import print_function. The future import only works under Python 2.6 and later, so for Python 2.5 and earlier you have two options. You can either convert the more complex print to something simpler, or you can use a separate print function that works under both Python2 and Python3.
>>> from __future__ import print_function
>>>
>>> def printex(*args, **kwargs):
... print(*args, file=sys.stderr, **kwargs)
...
>>> printex("hii")
hii
>>>
Case: Point to be noted that sys.stderr.write() or sys.stdout.write() ( stdout (standard output) is a pipe that is built into every UNIX/Linux system) is not a replacement for print, but yes we can use it as a alternative in some case. Print is a wrapper which wraps the input with space and newline at the end and uses the write function to write. This is the reason sys.stderr.write() is faster.
Note: we can also trace and debugg using Logging
#test.py
import logging
logging.info('This is the existing protocol.')
FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning("Protocol problem: %s", "connection reset", extra=d)
https://docs.python.org/2/library/logging.html#logger-objects
Sometimes we need a code block where we need to perform some operation right after setState where we are sure the state is being updated. That is where setState callback comes into play
For example, there was a scenario where I needed to enable a modal for 2 customers out of 20 customers, for the customers where we enabled it, there was a set of time taking API calls, so it looked like this
async componentDidMount() {
const appConfig = getCustomerConfig();
this.setState({enableModal: appConfig?.enableFeatures?.paymentModal }, async
()=>{
if(this.state.enableModal){
//make some API call for data needed in poput
}
});
}
enableModal boolean was required in UI blocks in the render function as well, that's why I did setState here, otherwise, could've just checked condition once and either called API set or not.
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
I had the same problem on Ubuntu
and the other solutions didn't help me.
I finally realized what my problem was. I had created my ssh
keys in /root/.ssh
folder, So even when I ran ssh-add
as root, it couldn't do its work and keep saying
Could not open a connection to your authentication agent.
I created my ssh public and private keys in /home/myUsername/
folder and I used
ssh-agent /bin/sh
then I ran
ssh-add /home/myUsername/.ssh/id_rsa
and problem was solved this way.
Note: For accessing your repository on git
add your git password when you are creating ssh
keys with ssh-keygen -t rsa -C "your git email here"
.
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
I use the following customization in Laravel to:
First, I'll create a file, helpers.php
, in the root of Laravel and insert the following:
<?php
if (!function_exists('database_driver')) {
function database_driver(): string
{
$connection = config('database.default');
return config('database.connections.' . $connection . '.driver');
}
}
if (!function_exists('is_database_driver')) {
function is_database_driver(string $driver): bool
{
return $driver === database_driver();
}
}
In composer.json, I'll insert the following into autoload
. This allows composer to auto-discover helpers.php.
"autoload": {
"files": [
"app/Services/Uploads/Processors/processor_functions.php",
"app/helpers.php"
]
},
I use the following in my Laravel models.
if (is_database_driver('sqlite')) {
$table->timestamps();
} else {
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')
->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
}
This allows my team to continue using sqlite for unit tests. ON UPDATE CURRENT_TIMESTAMP
is a MySQL shortcut and is not available in sqlite.
By changing one level in the "logging.config.dictConfig" you'll be able to take the whole logging level to a new level.
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'console': {
'format': '%(name)-12s %(levelname)-8s %(message)s'
},
'file': {
'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'console'
},
#CHANGE below level from DEBUG to THE_LEVEL_YOU_WANT_TO_SWITCH_FOR
#if we jump from DEBUG to INFO
# we won't be able to see the DEBUG logs in our logging.log file
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'formatter': 'file',
'filename': 'logging.log'
},
},
'loggers': {
'': {
'level': 'DEBUG',
'handlers': ['console', 'file'],
'propagate': False,
},
}
})
A simple example:
public class Test extends Thread {
public synchronized void run() {
for (int i = 0; i <= 10; i++) {
System.out.println("i::"+i);
}
}
public static void main(String[] args) {
Test obj = new Test();
Thread t1 = new Thread(obj);
Thread t2 = new Thread(obj);
Thread t3 = new Thread(obj);
t1.start();
t2.start();
t3.start();
}
}
Usually, instance methods are global methods. That means they are available in all instances of the class on which they were defined. In contrast, a singleton method is implemented on a single object.
Ruby stores methods in classes and all methods must be associated with a class. The object on which a singleton method is defined is not a class (it is an instance of a class). If only classes can store methods, how can an object store a singleton method? When a singleton method is created, Ruby automatically creates an anonymous class to store that method. These anonymous classes are called metaclasses, also known as singleton classes or eigenclasses. The singleton method is associated with the metaclass which, in turn, is associated with the object on which the singleton method was defined.
If multiple singleton methods are defined within a single object, they are all stored in the same metaclass.
class Zen
end
z1 = Zen.new
z2 = Zen.new
class << z1
def say_hello
puts "Hello!"
end
end
z1.say_hello # Output: Hello!
z2.say_hello # Output: NoMethodError: undefined method `say_hello'…
In the above example, class << z1 changes the current self to point to the metaclass of the z1 object; then, it defines the say_hello method within the metaclass.
Classes are also objects (instances of the built-in class called Class). Class methods are nothing more than singleton methods associated with a class object.
class Zabuton
class << self
def stuff
puts "Stuffing zabuton…"
end
end
end
All objects may have metaclasses. That means classes can also have metaclasses. In the above example, class << self modifies self so it points to the metaclass of the Zabuton class. When a method is defined without an explicit receiver (the class/object on which the method will be defined), it is implicitly defined within the current scope, that is, the current value of self. Hence, the stuff method is defined within the metaclass of the Zabuton class. The above example is just another way to define a class method. IMHO, it's better to use the def self.my_new_clas_method syntax to define class methods, as it makes the code easier to understand. The above example was included so we understand what's happening when we come across the class << self syntax.
Additional info can be found at this post about Ruby Classes.
File "C:\pythonwork\readthefile080410.py", line 120, in medications_minimum3
counter[row[11]]+=1
TypeError: unhashable type: 'list'
row[11]
is unhashable. It's a list. That is precisely (and only) what the error message means. You might not like it, but that is the error message.
Do this
counter[tuple(row[11])]+=1
Also, simplify.
d= [ row for row in c if counter[tuple(row[11])]>=sample_cutoff ]
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script> <script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>
Better option is use SQLQuery#addScalar than casting to Long
or BigDecimal
.
Here is modified query that returns count
column as Long
Query query = session
.createSQLQuery("SELECT COUNT(*) as count
FROM SpyPath
WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY)
GROUP BY DATE(time)
ORDER BY time;")
.addScalar("count", LongType.INSTANCE);
Then
List<Long> result = query.list(); //No ClassCastException here
Related link
Hibernate.LONG
, remember it has been deprecated since Hibernate version 3.6.XLongType.INSTANCE
Just add position:absolute; top:0; right:0;
to the CSS for your button.
#button {
line-height: 12px;
width: 18px;
font-size: 8pt;
font-family: tahoma;
margin-top: 1px;
margin-right: 2px;
position:absolute;
top:0;
right:0;
}
Here is a link that can help you to change the color of the Spinner:
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:textSize="20sp"
android:entries="@array/planets"/>
You need to create your own layout file with a custom definition for the spinner item spinner_item.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="#ff0000" />
If you want to customize the dropdown list items, you will need to create a new layout file. spinner_dropdown_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:maxLines="1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:ellipsize="marquee"
android:textColor="#aa66cc"/>
And finally another change in the declaration of the spinner:
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
R.array.planets_array, R.layout.spinner_item);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spinner.setAdapter(adapter);
That's it.
It's really useful, I used it with a slight change:
filename=directory.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.startsWith(ipro);
}
});
Another way with xargs
docker image ls -q | xargs -I {} docker image rm -f {}
In addition to Gilson PJ answer:
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
with
"scripts": {
"build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.
You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
and
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
Try to do all the steps specified in the link below and before that upgrade VirtualBox to 4.2 by following the instructions in VirtualBox 4.2.0 Released With Support For Drag'n'drop From Host To Linux Guests, More. Then upgrade Genymotion to the latest version.
Go to the desktop and run Genymotion. Select a virtual device with Android version 4.2 and then drag and drop the two files Genymotion-ARM-Translation_v1.1.zip first. Then Genymotion will show progress and after this it will promt a dialog. Then click OK and it will ask to reboot the device. Restart ADB. Do the same steps for the second file, gapps-jb-20130812-signed.zip and restart ADB.
I hope this will resolve the issue. Check this link - it explains it clearer.
Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.
They also provide exception handling, just like normal code, you can return from a promise or you can throw.
What you'd want in synchronous code is:
try{
try{
var res = $http.getSync("url");
res = someProcessingOf(res);
} catch (e) {
console.log("Got an error!",e);
throw e; // rethrow to not marked as handled
}
// do more stuff with res
} catch (e){
// handle errors in processing or in error.
}
The promisified version is very similar:
$http.get("url").
then(someProcessingOf).
catch(function(e){
console.log("got an error in initial processing",e);
throw e; // rethrow to not marked as handled,
// in $q it's better to `return $q.reject(e)` here
}).then(function(res){
// do more stuff
}).catch(function(e){
// handle errors in processing or in error.
});
The only way I've found to work with files on SharePoint while having to server rights is to map the WebDAV folder to a drive letter. Here's an example for the implementation.
Add references to the following ActiveX libraries in VBA:
wshom.ocx
) - for WshNetworkscrrun.dll
) - for FileSystemObjectCreate a new class module, call it DriveMapper
and add the following code:
Option Explicit
Private oMappedDrive As Scripting.Drive
Private oFSO As New Scripting.FileSystemObject
Private oNetwork As New WshNetwork
Private Sub Class_Terminate()
UnmapDrive
End Sub
Public Function MapDrive(NetworkPath As String) As Scripting.Folder
Dim DriveLetter As String, i As Integer
UnmapDrive
For i = Asc("Z") To Asc("A") Step -1
DriveLetter = Chr(i)
If Not oFSO.DriveExists(DriveLetter) Then
oNetwork.MapNetworkDrive DriveLetter & ":", NetworkPath
Set oMappedDrive = oFSO.GetDrive(DriveLetter)
Set MapDrive = oMappedDrive.RootFolder
Exit For
End If
Next i
End Function
Private Sub UnmapDrive()
If Not oMappedDrive Is Nothing Then
If oMappedDrive.IsReady Then
oNetwork.RemoveNetworkDrive oMappedDrive.DriveLetter & ":"
End If
Set oMappedDrive = Nothing
End If
End Sub
Then you can implement it in your code:
Sub test()
Dim dm As New DriveMapper
Dim sharepointFolder As Scripting.Folder
Set sharepointFolder = dm.MapDrive("http://your/sharepoint/path")
Debug.Print sharepointFolder.Path
End Sub
Just Remove The Browser Default
Margin
andPadding
Apply Top Of Your Css.
<style>
* {
margin: 0;
padding: 0;
}
</style>
NOTE:
html elements
before writing your css.OR [ Use This In Your Case
]
<style>
*{
margin: 0px;
padding: 0px;
}
h1 {
margin-top: 0px;
}
</style>
DEMO:
<style>_x000D_
_x000D_
*{_x000D_
margin: 0px;_x000D_
padding: 0px;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
margin-top: 0px;_x000D_
}_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<h1>logo</h1>_x000D_
</body>_x000D_
</html>
_x000D_
Happened to me too when I used this :
class App extends React.Component(){
}
Instead of the right one :
class App extends React.Component{
}
Notice:- () in the first one which is the main cause of this problem
In case anyone still hunting the cause of this hateful issue, there comes a solution to nail the causing file. https://www.drupal.org/node/1622904#comment-10768958 from Drupal
community.
And I quote:
Edit
includes/bootstrap.inc:
function drupal_load()
. It is a short function. Find following line:
include_once DRUPAL_ROOT . '/' . $filename;
Temporarily replace it by
ob_start();
include_once DRUPAL_ROOT . '/' . $filename;
$value = ob_get_contents();
ob_end_clean();
if ($value !== '') {
$filename = check_plain($filename);
$value = check_plain($value);
print "File '$filename' produced unforgivable content: '$value'.";
exit;
}
I encountered the same error message but don't have any access to the table like "dba_free_space" because I am not a dba. I use some previous answers to check available space and I still have a lot of space. However, after reducing the full table scan as many as possible. The problem is solved. My guess is that Oracle uses temp table to store the full table scan data. It the data size exceeds the limit, it will show the error. Hope this helps someone with the same issue
For R code I use
\usepackage{listings}
\lstset{
language=R,
basicstyle=\scriptsize\ttfamily,
commentstyle=\ttfamily\color{gray},
numbers=left,
numberstyle=\ttfamily\color{gray}\footnotesize,
stepnumber=1,
numbersep=5pt,
backgroundcolor=\color{white},
showspaces=false,
showstringspaces=false,
showtabs=false,
frame=single,
tabsize=2,
captionpos=b,
breaklines=true,
breakatwhitespace=false,
title=\lstname,
escapeinside={},
keywordstyle={},
morekeywords={}
}
And it looks exactly like this
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
Split and join the URL:
const s = 'http://free-proxy.cz/en/abc'
console.log(s.split('/').slice(0,3).join('/'))
I'm new to node.js (about 2 weeks), but I've just created a module that recursively reports to the console the contents of an object. It will list all or search for a specific item and then drill down by a given depth if need be.
Perhaps you can customize this to fit your needs. Keep It Simple! Why complicate?...
'use strict';
//console.log("START: AFutils");
// Recusive console output report of an Object
// Use this as AFutils.reportObject(req, "", 1, 3); // To list all items in req object by 3 levels
// Use this as AFutils.reportObject(req, "headers", 1, 10); // To find "headers" item and then list by 10 levels
// yes, I'm OLD School! I like to see the scope start AND end!!! :-P
exports.reportObject = function(obj, key, level, deep)
{
if (!obj)
{
return;
}
var nextLevel = level + 1;
var keys, typer, prop;
if(key != "")
{ // requested field
keys = key.split(']').join('').split('[');
}
else
{ // do for all
keys = Object.keys(obj);
}
var len = keys.length;
var add = "";
for(var j = 1; j < level; j++)
{
// I would normally do {add = add.substr(0, level)} of a precreated multi-tab [add] string here, but Sublime keeps replacing with spaces, even with the ["translate_tabs_to_spaces": false] setting!!! (angry)
add += "\t";
}
for (var i = 0; i < len; i++)
{
prop = obj[keys[i]];
if(!prop)
{
// Don't show / waste of space in console window...
//console.log(add + level + ": UNDEFINED [" + keys[i] + "]");
}
else
{
typer = typeof(prop);
if(typer == "function")
{
// Don't bother showing fundtion code...
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
}
else
if(typer == "object")
{
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "}");
if(nextLevel <= deep)
{
// drop the key search mechanism if first level item has been found...
this.reportObject(prop, "", nextLevel, deep); // Recurse into
}
}
else
{
// Basic report
console.log(add + level + ": [" + keys[i] + "] = {" + typer + "} = " + prop + ".");
}
}
}
return ;
};
//console.log("END: AFutils");
Instead of using jQuery, use css property text-overflow:ellipsis
. It will automatically truncate the string.
.truncated { display:inline-block;
max-width:100px;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
you can join both tables even on UPDATE
statements,
UPDATE a
SET a.marks = b.marks
FROM tempDataView a
INNER JOIN tempData b
ON a.Name = b.Name
for faster performance, define an INDEX
on column marks
on both tables.
using SUBQUERY
UPDATE tempDataView
SET marks =
(
SELECT marks
FROM tempData b
WHERE tempDataView.Name = b.Name
)
Support for the extended ternary operator was added in Twig 1.12.0.
If foo
echo yes
else echo no
:
{{ foo ? 'yes' : 'no' }}
If foo
echo it, else echo no
:
{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
If foo
echo yes
else echo nothing:
{{ foo ? 'yes' }}
or
{{ foo ? 'yes' : '' }}
Returns the value of foo
if it is defined and not null, no
otherwise:
{{ foo ?? 'no' }}
Returns the value of foo
if it is defined (empty values also count), no
otherwise:
{{ foo|default('no') }}
most simple way,
use set().difference(set())
list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))
answer is set([1])
can print as a list,
print list(set(list_a).difference(set(list_b)))
awk -F, '{ print $3, $0 }' user.csv | sort -nk2
and for reverse order
awk -F, '{ print $3, $0 }' user.csv | sort -nrk2
What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.
It is unclear to me whether you want both children of the main div or not. If so, use this:
div.section > div
If you only want the header, use this:
div.section > div:first-child
Using the >
changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.
Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.
Actually, there is a better way to do it than split:
public string GetFirstFromSplit(string input, char delimiter)
{
var i = input.IndexOf(delimiter);
return i == -1 ? input : input.Substring(0, i);
}
And as extension methods:
public static string FirstFromSplit(this string source, char delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
public static string FirstFromSplit(this string source, string delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
Usage:
string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"
SELECT DISTINCT
phuongxa.maxa ,
quanhuyen.mahuyen ,
phuongxa.tenxa ,
quanhuyen.tenhuyen ,
ISNULL(dkcd.tong, 0) AS tongdkcd
FROM phuongxa ,
quanhuyen
LEFT OUTER JOIN ( SELECT khaosat.maxa ,
COUNT(*) AS tong
FROM khaosat
WHERE CONVERT(DATETIME, ngaylap, 103) BETWEEN 'Sep 1 2011'
AND
'Sep 5 2011'
GROUP BY khaosat.maxa
) AS dkcd ON dkcd.maxa = maxa
WHERE phuongxa.maxa <> '99'
AND LEFT(phuongxa.maxa, 2) = quanhuyen.mahuyen
ORDER BY maxa;
Step 1: add your username to the docker
group:
sudo usermod -a -G docker $USER
Then logout and login again.
Step 2: Then change docker group ID :
newgrp docker
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...
import re
input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
input.write(each)
Use pd.concat
to merge a list of DataFrame into a single big DataFrame.
appended_data = []
for infile in glob.glob("*.xlsx"):
data = pandas.read_excel(infile)
# store DataFrame in list
appended_data.append(data)
# see pd.concat documentation for more info
appended_data = pd.concat(appended_data)
# write DataFrame to an excel sheet
appended_data.to_excel('appended.xlsx')
jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div
(or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.
I used require('http')
to consume https service and it showed "socket hang up
".
Then I changed require('http')
to require('https')
instead, and it is working.
For SQL2008,
Restart the server using configuration manager.
npm i -S lodash.uniqueid
Then in your code...
<script>
const uniqueId = require('lodash.uniqueid')
export default {
data () {
return {
id: ''
}
},
mounted () {
this.id = uniqueId()
}
}
</script>
This way you're not loading the entire lodash library, or even saving the entire library to node_modules
.
You can use any one way
NSString *string=[NSString stringWithFormat:@"%@",url1];
or
NSString *str=[url1 absoluteString];
NSLog(@"string :: %@",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(@"str :: %@", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
You can cheat! Say your div is 20px high, place the div at the top of the next container and set
position: absolute;
top: -20px;
It may not be semantically clean but does scale with responsive designs
You need 40 bits to represent the integer literal 600851475143. In Java, the maximum integer value is 2^31-1 however (i.e. integers are 32 bit, see http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html).
This has nothing to do with function
. Try using a long integer literal instead (as suggested in the other answers).
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>
use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
When a user connects, it should send a message to the server with a username which has to be unique, like an email.
A pair of username and socket should be stored in an object like this:
var users = {
'[email protected]': [socket object],
'[email protected]': [socket object],
'[email protected]': [socket object]
}
On the client, emit an object to the server with the following data:
{
to:[the other receiver's username as a string],
from:[the person who sent the message as string],
message:[the message to be sent as string]
}
On the server, listen for messages. When a message is received, emit the data to the receiver.
users[data.to].emit('receivedMessage', data)
On the client, listen for emits from the server called 'receivedMessage', and by reading the data you can handle who it came from and the message that was sent.
An easy way to do this is:
int main(int argc, char * argv[]){
std::cout << argv[0];
std::cin.get();
}
argv[]
is pretty much an array containing arguments you ran the .exe with, but the first one is always a path to the executable. If I build this the console shows:
C:\Users\Ulisse\source\repos\altcmd\Debug\currentdir.exe
You can use it like this, I hope you wont get outdated message now.
<td valign="top" style="white-space:nowrap" width="237">
As pointed by @ThiefMaster it is recommended to put width
and valign to CSS (note: CSS calls it vertical-align
).
1)
<td style="white-space:nowrap; width:237px; vertical-align:top;">
2) We can make a CSS class like this, it is more elegant way
In style section
.td-some-name
{
white-space:nowrap;
width:237px;
vertical-align:top;
}
In HTML section
<td class="td-some-name">
Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window
I know that it's an old question, but you can change the Response using a parameter (P):
public class Response<P> implements Serializable{
private static final long serialVersionUID = 1L;
public enum MessageCode {
SUCCESS, ERROR, UNKNOWN
}
private MessageCode code;
private String message;
private P payload;
...
public P getPayload() {
return payload;
}
public void setPayload(P payload) {
this.payload = payload;
}
}
The method would be
public Response<Departments> getDepartments(){...}
I can't try it now but it should works.
Otherwise it's possible to extends Response
@XmlRootElement
public class DepResponse extends Response<Department> {<no content>}
Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.
Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RegisterEvents();
}
private void RegisterEvents()
{
_tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
}
private void TboTest_TextChanged(object sender, EventArgs e)
{
// Change the text to bold on specified condition
if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
}
else
{
_tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
}
}
}
For hints, look closer at the class name name that throws an error and the line number, example: Compilation failure [ERROR] \applications\xxxxx.java:[44,30] error: cannot find symbol
One other cause is unsupported method of for java version say jdk7 vs 8. Check your %JAVA_HOME%
check it out:
http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html#getresource
ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)
if you make this int i[3] then i takes values i[0] i[1] i[2]
for your problem try this code structure
double[] array = new double[50];
for (int i = 0; i < 24; i++) {
}
for (int j = 25; j < 50; j++) {
}
As Mark (Amery) correctly notes: Using PyYaml's deserializer on a json dump works only if you have ASCII only. At least out of the box.
Two quick comments on the PyYaml approach:
NEVER use yaml.load on data from the field. Its a feature(!) of yaml to execute arbitrary code hidden within the structure.
You can make it work also for non ASCII via this:
def to_utf8(loader, node):
return loader.construct_scalar(node).encode('utf-8')
yaml.add_constructor(u'tag:yaml.org,2002:str', to_utf8)
But performance wise its of no comparison to Mark Amery's answer:
Throwing some deeply nested sample dicts onto the two methods, I get this (with dt[j] = time delta of json.loads(json.dumps(m))):
dt[yaml.safe_load(json.dumps(m))] =~ 100 * dt[j]
dt[byteify recursion(Mark Amery)] =~ 5 * dt[j]
So deserialization including fully walking the tree and encoding, well within the order of magnitude of json's C based implementation. I find this remarkably fast and its also more robust than the yaml load at deeply nested structures. And less security error prone, looking at yaml.load.
=> While I would appreciate a pointer to a C only based converter the byteify function should be the default answer.
This holds especially true if your json structure is from the field, containing user input. Because then you probably need to walk anyway over your structure - independent on your desired internal data structures ('unicode sandwich' or byte strings only).
Why?
Unicode normalisation. For the unaware: Take a painkiller and read this.
So using the byteify recursion you kill two birds with one stone:
In my tests it turned out that replacing the input.encode('utf-8') with a unicodedata.normalize('NFC', input).encode('utf-8') was even faster than w/o NFC - but thats heavily dependent on the sample data I guess.
I wrote an unpublished java app to monitor the clipboard, replacing items that offered text along with other richer formats, with items only offering the plain text format.
Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.
You would replace his .btn
with the following:
<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>
And add a small CSS for when the content is displayed:
.in.collapse+a.btn.showdetails:before {
content:'Hide details «';
}
.collapse+a.btn.showdetails:before {
content:'Show details »';
}
I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.6</version>
</dependency>
Very Simply Short week day name with Month and year
echo date('D, d-M-y');
output
Tue, 16-Feb-21
as per my requirements
return $item->start_time->format("D, d-M");
output
Tue, 16-Feb
Thats where asp.net puts dynamically compiled assemblies.
Created a directive (ng-repeat with lazy loading)
which loads data when it reaches to bottom of the page and remove half of the previously loaded data and when it reaches to top of the div again previous data(depending upon on page number) will be loaded removing half of the current data So on DOM at a time only limited data is present which may leads to better performance instead of rendering whole data on load.
HTML CODE:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ListController">
<div class="row customScroll" id="customTable" datafilter pagenumber="pageNumber" data="rowData" searchdata="searchdata" itemsPerPage="{{itemsPerPage}}" totaldata="totalData" selectedrow="onRowSelected(row,row.index)" style="height:300px;overflow-y: auto;padding-top: 5px">
<!--<div class="col-md-12 col-xs-12 col-sm-12 assign-list" ng-repeat="row in CRGC.rowData track by $index | orderBy:sortField:sortReverse | filter:searchFish">-->
<div class="col-md-12 col-xs-12 col-sm-12 pdl0 assign-list" style="padding:10px" ng-repeat="row in rowData" ng-hide="row[CRGC.columns[0].id]=='' && row[CRGC.columns[1].id]==''">
<!--col1-->
<div ng-click ="onRowSelected(row,row.index)"> <span>{{row["sno"]}}</span> <span>{{row["id"]}}</span> <span>{{row["name"]}}</span></div>
<!-- <div class="border_opacity"></div> -->
</div>
</div>
</body>
</html>
Angular CODE:
var app = angular.module('plunker', []);
var x;
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];
function ListController($scope, $timeout, $q, $templateCache) {
$scope.itemsPerPage = 40;
$scope.lastPage = 0;
$scope.maxPage = 100;
$scope.data = [];
$scope.pageNumber = 0;
$scope.makeid = function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$scope.DataFormFunction = function() {
var arrayObj = [];
for (var i = 0; i < $scope.itemsPerPage*$scope.maxPage; i++) {
arrayObj.push({
sno: i + 1,
id: Math.random() * 100,
name: $scope.makeid()
});
}
$scope.totalData = arrayObj;
$scope.totalData = $scope.totalData.filter(function(a,i){ a.index = i; return true; })
$scope.rowData = $scope.totalData.slice(0, $scope.itemsperpage);
}
$scope.DataFormFunction();
$scope.onRowSelected = function(row,index){
console.log(row,index);
}
}
angular.module('plunker').controller('ListController', ListController).directive('datafilter', function($compile) {
return {
restrict: 'EAC',
scope: {
data: '=',
totalData: '=totaldata',
pageNumber: '=pagenumber',
searchdata: '=',
defaultinput: '=',
selectedrow: '&',
filterflag: '=',
totalFilterData: '='
},
link: function(scope, elem, attr) {
//scope.pageNumber = 0;
var tempData = angular.copy(scope.totalData);
scope.totalPageLength = Math.ceil(scope.totalData.length / +attr.itemsperpage);
console.log(scope.totalData);
scope.data = scope.totalData.slice(0, attr.itemsperpage);
elem.on('scroll', function(event) {
event.preventDefault();
// var scrollHeight = angular.element('#customTable').scrollTop();
var scrollHeight = document.getElementById("customTable").scrollTop
/*if(scope.filterflag && scope.pageNumber != 0){
scope.data = scope.totalFilterData;
scope.pageNumber = 0;
angular.element('#customTable').scrollTop(0);
}*/
if (scrollHeight < 100) {
if (!scope.filterflag) {
scope.scrollUp();
}
}
if (angular.element(this).scrollTop() + angular.element(this).innerHeight() >= angular.element(this)[0].scrollHeight) {
console.log("scroll bottom reached");
if (!scope.filterflag) {
scope.scrollDown();
}
}
scope.$apply(scope.data);
});
/*
* Scroll down data append function
*/
scope.scrollDown = function() {
if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
scope.totalDataCompare = scope.totalData;
} else {
scope.totalDataCompare = scope.totalFilterData;
}
scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
if (scope.pageNumber < scope.totalPageLength - 1) {
scope.pageNumber++;
scope.lastaddedData = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage, (+attr.itemsperpage) + (+scope.pageNumber * attr.itemsperpage));
scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
scope.data = scope.data.concat(scope.lastaddedData);
scope.$apply(scope.data);
if (scope.pageNumber < scope.totalPageLength) {
var divHeight = $('.assign-list').outerHeight();
if (!scope.moveToPositionFlag) {
angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
} else {
scope.moveToPositionFlag = false;
}
}
}
}
/*
* Scroll up data append function
*/
scope.scrollUp = function() {
if (scope.defaultinput == undefined || scope.defaultinput == "") { //filter data append condition on scroll
scope.totalDataCompare = scope.totalData;
} else {
scope.totalDataCompare = scope.totalFilterData;
}
scope.totalPageLength = Math.ceil(scope.totalDataCompare.length / +attr.itemsperpage);
if (scope.pageNumber > 0) {
this.positionData = scope.data[0];
scope.data = scope.totalDataCompare.slice(scope.pageNumber * attr.itemsperpage - 0.5 * (+attr.itemsperpage), scope.pageNumber * attr.itemsperpage);
var position = +attr.itemsperpage * scope.pageNumber - 1.5 * (+attr.itemsperpage);
if (position < 0) {
position = 0;
}
scope.TopAddData = scope.totalDataCompare.slice(position, (+attr.itemsperpage) + position);
scope.pageNumber--;
var divHeight = $('.assign-list').outerHeight();
if (position != 0) {
scope.data = scope.TopAddData.concat(scope.data);
scope.$apply(scope.data);
angular.element('#customTable').scrollTop(divHeight * 1 * (+attr.itemsperpage));
} else {
scope.data = scope.TopAddData;
scope.$apply(scope.data);
angular.element('#customTable').scrollTop(divHeight * 0.5 * (+attr.itemsperpage));
}
}
}
}
};
});
Another Solution: If you using UI-grid in the project then same implementation is there in UI grid with infinite-scroll.
Depending upon height of the division it loads the data and upon scroll new data will be append and previous data will be removed.
HTML Code:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdn.rawgit.com/angular-ui/bower-ui-grid/master/ui-grid.min.css" type="text/css" />
<script data-require="[email protected]" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-grid/4.0.6/ui-grid.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="ListController">
<div class="input-group" style="margin-bottom: 15px">
<div class="input-group-btn">
<button class='btn btn-primary' ng-click="resetList()">RESET</button>
</div>
<input class="form-control" ng-model="search" ng-change="abc()">
</div>
<div data-ui-grid="gridOptions" class="grid" ui-grid-selection data-ui-grid-infinite-scroll style="height :400px"></div>
<button ng-click="getProductList()">Submit</button>
</body>
</html>
Angular Code:
var app = angular.module('plunker', ['ui.grid', 'ui.grid.infiniteScroll', 'ui.grid.selection']);
var x;
angular.module('plunker').controller('ListController', ListController);
ListController.$inject = ['$scope', '$timeout', '$q', '$templateCache'];
function ListController($scope, $timeout, $q, $templateCache) {
$scope.itemsPerPage = 200;
$scope.lastPage = 0;
$scope.maxPage = 5;
$scope.data = [];
var request = {
"startAt": "1",
"noOfRecords": $scope.itemsPerPage
};
$templateCache.put('ui-grid/selectionRowHeaderButtons',
"<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-row-selected': row.isSelected}\" ><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"row.isSelected\" ng-click=\"row.isSelected=!row.isSelected;selectButtonClick(row, $event)\"> </div>"
);
$templateCache.put('ui-grid/selectionSelectAllButtons',
"<div class=\"ui-grid-selection-row-header-buttons \" ng-class=\"{'ui-grid-all-selected': grid.selection.selectAll}\" ng-if=\"grid.options.enableSelectAll\"><input style=\"margin: 0; vertical-align: middle\" type=\"checkbox\" ng-model=\"grid.selection.selectAll\" ng-click=\"grid.selection.selectAll=!grid.selection.selectAll;headerButtonClick($event)\"></div>"
);
$scope.gridOptions = {
infiniteScrollDown: true,
enableSorting: false,
enableRowSelection: true,
enableSelectAll: true,
//enableFullRowSelection: true,
columnDefs: [{
field: 'sno',
name: 'sno'
}, {
field: 'id',
name: 'ID'
}, {
field: 'name',
name: 'My Name'
}],
data: 'data',
onRegisterApi: function(gridApi) {
gridApi.infiniteScroll.on.needLoadMoreData($scope, $scope.loadMoreData);
$scope.gridApi = gridApi;
}
};
$scope.gridOptions.multiSelect = true;
$scope.makeid = function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
$scope.abc = function() {
var a = $scope.search;
x = $scope.searchData;
$scope.data = x.filter(function(arr, y) {
return arr.name.indexOf(a) > -1
})
console.log($scope.data);
if ($scope.gridApi.grid.selection.selectAll)
$timeout(function() {
$scope.gridApi.selection.selectAllRows();
}, 100);
}
$scope.loadMoreData = function() {
var promise = $q.defer();
if ($scope.lastPage < $scope.maxPage) {
$timeout(function() {
var arrayObj = [];
for (var i = 0; i < $scope.itemsPerPage; i++) {
arrayObj.push({
sno: i + 1,
id: Math.random() * 100,
name: $scope.makeid()
});
}
if (!$scope.search) {
$scope.lastPage++;
$scope.data = $scope.data.concat(arrayObj);
$scope.gridApi.infiniteScroll.dataLoaded();
console.log($scope.data);
$scope.searchData = $scope.data;
// $scope.data = $scope.searchData;
promise.resolve();
if ($scope.gridApi.grid.selection.selectAll)
$timeout(function() {
$scope.gridApi.selection.selectAllRows();
}, 100);
}
}, Math.random() * 1000);
} else {
$scope.gridApi.infiniteScroll.dataLoaded();
promise.resolve();
}
return promise.promise;
};
$scope.loadMoreData();
$scope.getProductList = function() {
if ($scope.gridApi.selection.getSelectedRows().length > 0) {
$scope.gridOptions.data = $scope.resultSimulatedData;
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows(); //<--Property undefined error here
console.log($scope.mySelectedRows);
//alert('Selected Row: ' + $scope.mySelectedRows[0].id + ', ' + $scope.mySelectedRows[0].name + '.');
} else {
alert('Select a row first');
}
}
$scope.getSelectedRows = function() {
$scope.mySelectedRows = $scope.gridApi.selection.getSelectedRows();
}
$scope.headerButtonClick = function() {
$scope.selectAll = $scope.grid.selection.selectAll;
}
}
Relocate the project in an outer directory.
For example from C:/Users/x/desktop/AndroidProject
to C:/projects/AndroidProject
.
The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval()
and Bind()
, taking advantage of the strongly-typed bindings.
*Note: this will only work if you're not using a SqlDataSource
or an anonymous object
. It requires a Strongly-typed object (from an EF model or any other class).
This code snippet shows how Eval
and Bind
would be used for a ListView
control (InsertItem
needs Bind
, as explained by Darin Dimitrov above, and ItemTemplate
is read-only (hence they're labels), so just needs an Eval
):
<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
<InsertItemTemplate>
<li>
Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />
Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />
<asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />
</li>
</InsertItemTemplate>
<ItemTemplate>
<li>
Title: <asp:Label ID="Title" runat="server" Text='<%# Eval("Title") %>' /><br />
Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />
<asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
</li>
</ItemTemplate>
From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType
, which points to the type of object you're assigning to its data source.
<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>
Picture
is the strongly type object (from EF model). We then replace:
Bind(property) -> BindItem.property
Eval(property) -> Item.property
So this:
<%# Bind("Title") %>
<%# Bind("Description") %>
<%# Eval("Title") %>
<%# Eval("Description") %>
Would become this:
<%# BindItem.Title %>
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>
Advantages over Eval & Bind:
Source: from this excellent book
If we're going to mention regular expressions, we might as well mention the switch
statement.
var expr = 'Papayas';_x000D_
switch (expr) {_x000D_
case 'Oranges':_x000D_
console.log('Oranges are $0.59 a pound.');_x000D_
break;_x000D_
case 'Mangoes':_x000D_
case 'Papayas': // Mangoes or papayas_x000D_
console.log('Mangoes and papayas are $2.79 a pound.');_x000D_
// expected output: "Mangoes and papayas are $2.79 a pound."_x000D_
break;_x000D_
default:_x000D_
console.log('Sorry, we are out of ' + expr + '.');_x000D_
}
_x000D_
There are some gotchas. Assignment in Javascript is from right to left so when you write:
var moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
it effectively translates to:
var moveUp = (moveDown = (moveLeft = (moveRight = (mouseDown = (touchDown = false)))));
which effectively translates to:
var moveUp = (window.moveDown = (window.moveLeft = (window.moveRight = (window.mouseDown = (window.touchDown = false)))));
Inadvertently, you just created 5 global variables--something I'm pretty sure you didn't want to do.
Note: My above example assumes you are running your code in the browser, hence window
. If you were to be in a different environment these variables would attach to whatever the global context happens to be for that environment (i.e., in Node.js, it would attach to global
which is the global context for that environment).
Now you could first declare all your variables and then assign them to the same value and you could avoid the problem.
var moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown;
moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;
Long story short, both ways would work just fine, but the first way could potentially introduce some pernicious bugs in your code. Don't commit the sin of littering the global namespace with local variables if not absolutely necessary.
Sidenote: As pointed out in the comments (and this is not just in the case of this question), if the copied value in question was not a primitive value but instead an object, you better know about copy by value vs copy by reference. Whenever assigning objects, the reference to the object is copied instead of the actual object. All variables will still point to the same object so any change in one variable will be reflected in the other variables and will cause you a major headache if your intention was to copy the object values and not the reference.
The problem was that I needed to have both minGW and MSYS installed and added to PATH.
The problem is now fixed.
$("a.more").click(function() {
$.fancybox({
'padding' : 0,
'autoScale' : false,
'transitionIn' : 'none',
'transitionOut' : 'none',
'title' : this.title,
'width' : 680,
'height' : 495,
'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type' : 'swf', // <--add a comma here
'swf' : {'allowfullscreen':'true'} // <-- flashvars here
});
return false;
});
You can run specific lines of script by highlighting them and clicking shift + ctrl + b
You can also use command line by going to the root folder and writing:
$ node nameOfFile.js
$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
If you need some complete solution, you can use this :
http://jsfiddle.net/7Vv8u/2703/
JS (jQuery)
var text = $('.text-overflow'),
btn = $('.btn-overflow'),
h = text.scrollHeight;
if(h > 120) {
btn.addClass('less');
btn.css('display', 'block');
}
btn.click(function(e)
{
e.stopPropagation();
if (btn.hasClass('less')) {
btn.removeClass('less');
btn.addClass('more');
btn.text('Show less');
text.animate({'height': h});
} else {
btn.addClass('less');
btn.removeClass('more');
btn.text('Show more');
text.animate({'height': '120px'});
}
});
HTML
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<a class="btn-overflow" href="#">Show more</a>
CSS
.text-overflow {
width:250px;
height:120px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}
.btn-overflow {
display: none;
text-decoration: none;
}
If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:
public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T), true);
return atts.Length > 0;
}
which you can use like typeof(Foo).HasAttribute<BarAttribute>();
Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:
ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()
Add CDN Files of toastr.css and toastr.js
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
function toasterOptions() {
toastr.options = {
"closeButton": false,
"debug": false,
"newestOnTop": false,
"progressBar": true,
"positionClass": "toast-top-center",
"preventDuplicates": true,
"onclick": null,
"showDuration": "100",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "show",
"hideMethod": "hide"
};
};
toasterOptions();
toastr.error("Error Message from toastr");
Let's suppose you have two different classes:
public class Person
{
public string Name, Email;
public Person(string name, string email)
{
Name = name;
Email = email;
}
}
class Data
{
public string Mail, SlackId;
public Data(string mail, string slackId)
{
Mail = mail;
SlackId = slackId;
}
}
Now, let's Prepare data to work with:
var people = new Person[]
{
new Person("Sudi", "[email protected]"),
new Person("Simba", "[email protected]"),
new Person("Sarah", string.Empty)
};
var records = new Data[]
{
new Data("[email protected]", "Sudi_Try"),
new Data("[email protected]", "Sudi@Test"),
new Data("[email protected]", "SimbaLion")
};
You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.
Let's now construct the query to join Person with Data:
var query = people.Join(records,
x => x.Email,
y => y.Mail,
(person, record) => new { Name = person.Name, SlackId = record.SlackId});
Console.WriteLine(query);
After constructing the query, you could also iterate over it with a foreach like so:
foreach (var item in query)
{
Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
}
Let's also output the result for GroupJoin:
Console.WriteLine(
people.GroupJoin(
records,
x => x.Email,
y => y.Mail,
(person, recs) => new {
Name = person.Name,
SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
}
));
You will notice that the GroupJoin will put all SlackIds in a single group.
Fur future readers, if you are using Angular 1.6, you also need to change the hashPrefix
:
appModule.config(['$locationProvider', function($locationProvider) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix('');
}]);
Don't forget to set the base in your HTML <head>
:
<head>
<base href="/">
...
</head>
More info about the changelog here.
The capitalization is wrong, and you have an extra argument.
Do this instead:
$('img#thumb').removeAttr('id');
For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.
Use .apply()
to have the same access to arguments
in function b
, like this:
function a(){
b.apply(null, arguments);
}
function b(){
alert(arguments); //arguments[0] = 1, etc
}
a(1,2,3);?
<?php echo date("Y"); ?>
I have one strategy to settle your problem. You can use the application of proxy to modify or monitor your net status. e.g, Charles.
You ought to change the default config of the Charles like the following picture I posted.
And finally, you will discover the net status has been shaped into lower pace.
With a virtual machine, we have a server, we have a host operating system on that server, and then we have a hypervisor. And then running on top of that hypervisor, we have any number of guest operating systems with an application and its dependent binaries, and libraries on that server. It brings a whole guest operating system with it. It's quite heavyweight. Also there's a limit to how much you can actually put on each physical machine.
Docker containers on the other hand, are slightly different. We have the server. We have the host operating system. But instead a hypervisor, we have the Docker engine, in this case. In this case, we're not bringing a whole guest operating system with us. We're bringing a very thin layer of the operating system, and the container can talk down into the host OS in order to get to the kernel functionality there. And that allows us to have a very lightweight container.
All it has in there is the application code and any binaries and libraries that it requires. And those binaries and libraries can actually be shared across different containers if you want them to be as well. And what this enables us to do, is a number of things. They have much faster startup time. You can't stand up a single VM in a few seconds like that. And equally, taking them down as quickly.. so we can scale up and down very quickly and we'll look at that later on.
Every container thinks that it’s running on its own copy of the operating system. It’s got its own file system, own registry, etc. which is a kind of a lie. It’s actually being virtualized.
Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.
I would do an XOR each charAt() to create a new String. Like
String s, key;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();
In response to @user467257's comment
If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).
It is the char
values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.
public static void main(String... args) throws UnsupportedEncodingException {
char ch1 = 'a';
char ch2 = 'æ';
char ch3 = (char) (ch1 ^ ch2);
System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}
prints
135 UTF-8 encoded is [-62, -121]
<input [disabled]="is_edit" id="name" type="text">
<button (click)="is_edit = !is_edit">Change input state</button>
export class AppComponent {
is_edit : boolean = false;
}
This links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
In my case my RecyclerView
have a padding top like this
<android.support.v7.widget.RecyclerView
...
android:paddingTop="100dp"
android:clipToPadding="false"
/>
Then for scroll a item to top, I need to
recyclerViewLinearLayoutManager.scrollToPositionWithOffset(position, -yourRecyclerView.getPaddingTop());
Do something like this:
<script>
function changeColor(id)
{
document.getElementById(id).style.color = "#ff0000"; // forecolor
document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>
<div id="myid">Hello There !!</div>
<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>
Use below function with below example for changing image size :
//Example :
System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg");
System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100);
//image size modification unction
public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight)
{
Bitmap outputImage = null;
Graphics graphics = null;
try
{
outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555);
graphics = Graphics.FromImage(outputImage);
graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight),
new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
return outputImage;
}
catch (Exception ex)
{
return img;
}
}
Even after enabling Intel Virtualization Technology (Intel VT-x), I got the error message ' dev/kvm not found ' in Android Studio.by making Hyper-V feature off in Windows 8.1 issue was fixed.
here is how to access Windows Hyper-V feature
Control Panel -> Programs and Features -> Turn Windows features on and off.
This workaround is dangerous and not recommended:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
It's not a good idea to disable SSL peer verification. Doing so might expose your requests to MITM attackers.
In fact, you just need an up-to-date CA root certificate bundle. Installing an updated one is as easy as:
Downloading up-to-date cacert.pem
file from cURL website and
Setting a path to it in your php.ini file, e.g. on Windows:
curl.cainfo=c:\php\cacert.pem
That's it!
Stay safe and secure.
An unofficial 64-bit Windows build is available from Apache Lounge.
I'd like to say the difference is purely stylistic, but I'm really having my doubts. Consider the following example:
/*
Add trim() functionality to JavaScript...
1. By extending the String prototype
2. By creating a 'stand-alone' function
This is just to demonstrate results are the same in both cases.
*/
// Extend the String prototype with a trim() method
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
// 'Stand-alone' trim() function
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
};
document.writeln(String.prototype.trim);
document.writeln(trim);
In Safari, Chrome, Opera, and Internet Explorer (tested in Internet Explorer 7 and Internet Explorer 8), this will return the following:
function () {
return this.replace(/^\s+|\s+$/g, '');
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, '');
}
However, Firefox will yield a slightly different result:
function () {
return this.replace(/^\s+|\s+$/g, "");
}
function trim(str) {
return str.replace(/^\s+|\s+$/g, "");
}
The single quotes have been replaced by double quotes. (Also note how the indenting space was replaced by four spaces.) This gives the impression that at least one browser parses JavaScript internally as if everything was written using double quotes. One might think, it takes Firefox less time to parse JavaScript if everything is already written according to this 'standard'.
Which, by the way, makes me a very sad panda, since I think single quotes look much nicer in code. Plus, in other programming languages, they're usually faster to use than double quotes, so it would only make sense if the same applied to JavaScript.
Conclusion: I think we need to do more research on this.
This might explain Peter-Paul Koch's test results from back in 2003.
It seems that single quotes are sometimes faster in Explorer Windows (roughly 1/3 of my tests did show a faster response time), but if Mozilla shows a difference at all, it handles double quotes slightly faster. I found no difference at all in Opera.
2014: Modern versions of Firefox/Spidermonkey don’t do this anymore.
I always go with the generic css title with my setup. I'm just building analytics for my blog admin page. I don't need anything fancy. Here's some code...
let comps = g.selectAll('.myClass')
.data(data)
.enter()
.append('rect')
...styling...
...transitions...
...whatever...
g.selectAll('.myClass')
.append('svg:title')
.text((d, i) => d.name + '-' + i);
And a screenshot of chrome...
I don't think you can tell with the std::string class. However, if you really need this information, you could always derive a class from std::string and give the derived class the ability to tell if it had been changed since construction (or some other arbitrary time). Or better yet, just write a new class that wraps std::string since deriving from std::string may not be a good idea given the lack of a base class virtual destructor. That's probably more work, but more work tends to be needed for an optimal solution.
Of course, you can always just assume if it contains something other than "" then it has been "set", this won't detect it manually getting set to "" though.
git branch
with no arguments displays the current branch marked with an asterisk in front of it:
user@host:~/gittest$ git branch
* master
someotherbranch
In order to not have to type this all the time, I can recommend git prompt:
https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh
In the AIX box how I can see that I am using master or inside a particular branch. What changes inside .git that drives which branch I am on?
Git stores the HEAD
in the file .git/HEAD
. If you're on the master
branch, it could look like this:
$ cat .git/HEAD
ref: refs/heads/master
I use SharePrefrences:
package myapps.serializedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the SharedPreferences
SharedPreferences sharedPreferences = this.getSharedPreferences("myapps.serilizerdemo", Context.MODE_PRIVATE);
ArrayList<String> friends = new ArrayList<>();
friends.add("Jack");
friends.add("Joe");
try {
//Write / Serialize
sharedPreferences.edit().putString("friends",
ObjectSerializer.serialize(friends)).apply();
} catch (IOException e) {
e.printStackTrace();
}
//READ BACK
ArrayList<String> newFriends = new ArrayList<>();
try {
newFriends = (ArrayList<String>) ObjectSerializer.deserialize(
sharedPreferences.getString("friends", ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
}
Log.i("***NewFriends", newFriends.toString());
}
}
As already answered by @Bruno you need to use pageEvents.
Please check out the sample code below:
private void CreatePDF()
{
string fileName = string.Empty;
DateTime fileCreationDatetime = DateTime.Now;
fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));
string pdfPath = Server.MapPath(@"~\PDFs\") + fileName;
using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
{
//step 1
using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
{
try
{
// step 2
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
pdfWriter.PageEvent = new Common.ITextEvents();
//open the stream
pdfDoc.Open();
for (int i = 0; i < 10; i++)
{
Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));
para.Alignment = Element.ALIGN_CENTER;
pdfDoc.Add(para);
pdfDoc.NewPage();
}
pdfDoc.Close();
}
catch (Exception ex)
{
//handle exception
}
finally
{
}
}
}
}
And create one class file named ITextEvents.cs and add following code:
public class ITextEvents : PdfPageEventHelper
{
// This is the contentbyte object of the writer
PdfContentByte cb;
// we will put the final number of pages in a template
PdfTemplate headerTemplate, footerTemplate;
// this is the BaseFont we are going to use for the header / footer
BaseFont bf = null;
// This keeps track of the creation time
DateTime PrintTime = DateTime.Now;
#region Fields
private string _header;
#endregion
#region Properties
public string Header
{
get { return _header; }
set { _header = value; }
}
#endregion
public override void OnOpenDocument(PdfWriter writer, Document document)
{
try
{
PrintTime = DateTime.Now;
bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb = writer.DirectContent;
headerTemplate = cb.CreateTemplate(100, 100);
footerTemplate = cb.CreateTemplate(50, 50);
}
catch (DocumentException de)
{
}
catch (System.IO.IOException ioe)
{
}
}
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);
//Create PdfTable object
PdfPTable pdfTab = new PdfPTable(3);
//We will have to create separate cells to include image logo and 2 separate strings
//Row 1
PdfPCell pdfCell1 = new PdfPCell();
PdfPCell pdfCell2 = new PdfPCell(p1Header);
PdfPCell pdfCell3 = new PdfPCell();
String text = "Page " + writer.PageNumber + " of ";
//Add paging to header
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
//Adds "12" in Page 1 of 12
cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
}
//Add paging to footer
{
cb.BeginText();
cb.SetFontAndSize(bf, 12);
cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
cb.ShowText(text);
cb.EndText();
float len = bf.GetWidthPoint(text, 12);
cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
}
//Row 2
PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));
//Row 3
PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
PdfPCell pdfCell6 = new PdfPCell();
PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));
//set the alignment of all three cells and set border to 0
pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;
pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.Colspan = 3;
pdfCell1.Border = 0;
pdfCell2.Border = 0;
pdfCell3.Border = 0;
pdfCell4.Border = 0;
pdfCell5.Border = 0;
pdfCell6.Border = 0;
pdfCell7.Border = 0;
//add all three cells into PdfTable
pdfTab.AddCell(pdfCell1);
pdfTab.AddCell(pdfCell2);
pdfTab.AddCell(pdfCell3);
pdfTab.AddCell(pdfCell4);
pdfTab.AddCell(pdfCell5);
pdfTab.AddCell(pdfCell6);
pdfTab.AddCell(pdfCell7);
pdfTab.TotalWidth = document.PageSize.Width - 80f;
pdfTab.WidthPercentage = 70;
//pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;
//call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
//first param is start row. -1 indicates there is no end row and all the rows to be included to write
//Third and fourth param is x and y position to start writing
pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
//set pdfContent value
//Move the pointer and draw line to separate header section from rest of page
cb.MoveTo(40, document.PageSize.Height - 100);
cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
cb.Stroke();
//Move the pointer and draw line to separate footer section from rest of page
cb.MoveTo(40, document.PageSize.GetBottom(50) );
cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
cb.Stroke();
}
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
headerTemplate.BeginText();
headerTemplate.SetFontAndSize(bf, 12);
headerTemplate.SetTextMatrix(0, 0);
headerTemplate.ShowText((writer.PageNumber - 1).ToString());
headerTemplate.EndText();
footerTemplate.BeginText();
footerTemplate.SetFontAndSize(bf, 12);
footerTemplate.SetTextMatrix(0, 0);
footerTemplate.ShowText((writer.PageNumber - 1).ToString());
footerTemplate.EndText();
}
}
I hope it helps!
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
%8s would specify a minimum width of 8 characters. You want to truncate at 8, so use %.8s.
If you want to always print exactly 8 characters you could use %8.8s
If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
You can use Enum.Parse
like, if it is string
AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")
Here is all you need:
curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true); // enable tracking
... // do curl request
$headerSent = curl_getinfo($curlHandle, CURLINFO_HEADER_OUT ); // request headers
MVC i have two input text 1: number of day 2: datetime picker
@Html.TextBox("HeaderINVID", null, new { @id = "HeaderINVID", @type = "number", @class = "form-control", autocomplete = "off", placeholder = "Day Count " })
@Html.TextBox("HeaderINVDT", null, new { id = "HeaderINVDT", @class = "form-control format-picker", autocomplete = "off", placeholder = " Date" })
javascipt
to calculate number from date use
$("#HeaderINVID").bind("keyup", function (e) {
var INVID = $("#HeaderINVID").val();
var date = moment()
.add(INVID, 'd')
.toDate();
$("#HeaderINVDT").val(moment(date).format('YYYY-MM-DD')) ;
})
to calculate number of days between two dates use
$("#HeaderINVDT").bind('change', function (e) {
var StDT = moment($("#HeaderINVDT").val()).startOf('day');
var NODT = moment().startOf('day');
$("#HeaderINVID").val(StDT.diff(NODT, 'days'));
})
do not forget to add http://momentjs.com/
The same result can be achieved using Lodash.
var result1 = [_x000D_
{id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
{id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
{id:3, name:'Peter', type:'user', username:'pete'},_x000D_
{id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
{id:2, name:'John', email:'[email protected]'},_x000D_
{id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var result3 = _(result1) _x000D_
.differenceBy(result2, 'id', 'name')_x000D_
.map(_.partial(_.pick, _, 'id', 'name'))_x000D_
.value();_x000D_
_x000D_
console.log(result3);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).
Lastly, you have to map the result in order to "omit" the undesired properties of the object.
Hope it helps.
a = [0,1,2,3]
a.drop(1)
# => [1, 2, 3]
a
# => [0,1,2,3]
and additionally:
[0,1,2,3].drop(2)
=> [2, 3]
[0,1,2,3].drop(3)
=> [3]
Sure, you can put your constants into a separate module. For example:
const.py:
A = 12
B = 'abc'
C = 1.2
main.py:
import const
print const.A, const.B, const.C
Note that as declared above, A
, B
and C
are variables, i.e. can be changed at run time.
You could subscribe for the onchange event on the input field:
<input type="file" id="file" name="file" />
and then:
document.getElementById('file').onchange = function() {
// fire the upload here
};
Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
http://www.csharp-examples.net/string-format-double/
edit
No idea why they used "String" instead of "string", but the rest is correct.
The topic is 'Embed image in a button element', and the question using plain HTML. I do this using the span tag in the same way that glyphicons are used in bootstrap. My image is 16 x 16px and can be any format.
Here's the plain HTML that answers the question:
<button type="button"><span><img src="images/xxx.png" /></span> Click Me</button>
Article on Programming.Guide: Switch on enum
enum MyEnum { CONST_ONE, CONST_TWO }
class Test {
public static void main(String[] args) {
MyEnum e = MyEnum.CONST_ONE;
switch (e) {
case CONST_ONE: System.out.println(1); break;
case CONST_TWO: System.out.println(2); break;
}
}
}
Switches for strings are implemented in Java 7.
Mike's answer is working good until you are using the "re-use" bind value.
For example:
SELECT * FROM `an_modules` AS `m` LEFT JOIN `an_module_sites` AS `ms` ON m.module_id = ms.module_id WHERE 1 AND `module_enable` = :module_enable AND `site_id` = :site_id AND (`module_system_name` LIKE :search OR `module_version` LIKE :search)
The Mike's answer can only replace first :search but not the second.
So, I rewrite his answer to work with multiple parameters that can re-used properly.
public function interpolateQuery($query, $params) {
$keys = array();
$values = $params;
$values_limit = [];
$words_repeated = array_count_values(str_word_count($query, 1, ':_'));
# build a regular expression for each parameter
foreach ($params as $key => $value) {
if (is_string($key)) {
$keys[] = '/:'.$key.'/';
$values_limit[$key] = (isset($words_repeated[':'.$key]) ? intval($words_repeated[':'.$key]) : 1);
} else {
$keys[] = '/[?]/';
$values_limit = [];
}
if (is_string($value))
$values[$key] = "'" . $value . "'";
if (is_array($value))
$values[$key] = "'" . implode("','", $value) . "'";
if (is_null($value))
$values[$key] = 'NULL';
}
if (is_array($values)) {
foreach ($values as $key => $val) {
if (isset($values_limit[$key])) {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, $values_limit[$key], $count);
} else {
$query = preg_replace(['/:'.$key.'/'], [$val], $query, 1, $count);
}
}
unset($key, $val);
} else {
$query = preg_replace($keys, $values, $query, 1, $count);
}
unset($keys, $values, $values_limit, $words_repeated);
return $query;
}
plt.plot(X,y)
function just draws the plot on the canvas. In order to view the plot, you have to specify plt.show()
after plt.plot(X,y)
. So,
import matplotlib.pyplot as plt
X = //your x
y = //your y
plt.plot(X,y)
plt.show()
I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.
Be careful of the accepted answer, it fails if the time_point is before the epoch.
This line of code:
std::size_t fractional_seconds = ms.count() % 1000;
will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).
Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)
One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.
Shamelessly copied from Generic deserialization of an xml string
public static T DeserializeFromXmlString<T>(string xmlString)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlString))
{
return (T) serializer.Deserialize(reader);
}
}