Add border-collapse:collapse
to your table rule:
table {
border-collapse: collapse;
}
table {
border-collapse: collapse;
}
tr {
border-bottom: 1pt solid black;
}
_x000D_
<table>
<tr><td>A1</td><td>B1</td><td>C1</td></tr>
<tr><td>A2</td><td>B2</td><td>C2</td></tr>
<tr><td>A2</td><td>B2</td><td>C2</td></tr>
</table>
_x000D_
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
I doubt very much a telnet library will ever be part of the .Net BCL, although you do have almost full socket support so it wouldnt be too hard to emulate a telnet client, Telnet in its general implementation is a legacy and dying technology that where exists generally sits behind a nice new modern facade. In terms of Unix/Linux variants you'll find that out the box its SSH and enabling telnet is generally considered poor practice.
You could check out: http://granados.sourceforge.net/ - SSH Library for .Net http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh
You'll still need to put in place your own wrapper to handle events for feeding in input in a scripted manner.
@Autowired
private EntityManager entityManager;
@RequestMapping("/authors/{fname}/{lname}")
public List actionAutherMulti(@PathVariable("fname") String fname, @PathVariable("lname") String lname) {
return entityManager.createQuery("select A from Auther A WHERE A.firstName = ?1 AND A.lastName=?2")
.setParameter(1, fname)
.setParameter(2, lname)
.getResultList();
}
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Timeconversion {
private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm", Locale.ENGLISH); //Specify your locale
public long timeConversion(String time) {
long unixTime = 0;
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:30")); //Specify your timezone
try {
unixTime = dateFormat.parse(time).getTime();
unixTime = unixTime / 1000;
} catch (ParseException e) {
e.printStackTrace();
}
return unixTime;
}
}
I solved by this simple trick.
<script type="text/javascript">
var style = 'assets/css/style.css?'+Math.random();;
</script>
<script type="text/javascript">
document.write('<link href="'+style+'" rel="stylesheet">');
</script>
In your class, where you implement the static function, you can call a private\public method from this class. The private\public method can access the getResources.
for example:
public class Text {
public static void setColor(EditText et) {
et.resetColor(); // it works
// ERROR
et.setTextColor(getResources().getColor(R.color.Black)); // ERROR
}
// set the color to be black when reset
private void resetColor() {
setTextColor(getResources().getColor(R.color.Black));
}
}
and from other class\activity, you can call:
Text.setColor('some EditText you initialized');
I found this can be done by drawing a rectangle inside the progress bar, and to set its width according to the progress's current value. I also added support for right to left progress. This way you don't need to use the Image, and since Rectnalge.Inflate isn't called the drawn rectangle is smaller.
public partial class CFProgressBar : ProgressBar
{
public CFProgressBar()
{
InitializeComponent();
this.SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaintBackground(PaintEventArgs pevent) { }
protected override void OnPaint(PaintEventArgs e)
{
double scaleFactor = (((double)Value - (double)Minimum) / ((double)Maximum - (double)Minimum));
int currentWidth = (int)((double)Width * scaleFactor);
Rectangle rect;
if (this.RightToLeftLayout)
{
int currentX = Width - currentWidth;
rect = new Rectangle(currentX, 0, this.Width, this.Height);
}
else
rect = new Rectangle(0, 0, currentWidth, this.Height);
if (rect.Width != 0)
{
SolidBrush sBrush = new SolidBrush(ForeColor);
e.Graphics.FillRectangle(sBrush, rect);
}
}
}
It depends on what you mean:
As mentioned String.hashCode()
gives you a 32 bit hash code.
If you want (say) a 64-bit hashcode you can easily implement it yourself.
If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.
If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.
A Java String of length N has 65536 ^ N
possible states, and requires an integer with 16 * N
bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N
bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)
But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.
The answer seems to be to use the header more than once. That is, rather than sending
Access-Control-Allow-Origin: http://domain1.example, http://domain2.example, http://domain3.example
send
Access-Control-Allow-Origin: http://domain1.example
Access-Control-Allow-Origin: http://domain2.example
Access-Control-Allow-Origin: http://domain3.example
On Apache, you can do this in an httpd.conf
<VirtualHost>
section or .htaccess
file using mod_headers
and this syntax:
Header add Access-Control-Allow-Origin "http://domain1.example"
Header add Access-Control-Allow-Origin "http://domain2.example"
Header add Access-Control-Allow-Origin "http://domain3.example"
The trick is to use add
rather than append
as the first argument.
It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.
For asp core 2.2:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;
namespace Project
{
sealed class Program
{
#region Variables
/// <summary>
/// Last loaded configuration
/// </summary>
private static IConfiguration _Configuration;
#endregion
#region Properties
/// <summary>
/// Default application configuration
/// </summary>
internal static IConfiguration Configuration
{
get
{
// None configuration yet?
if (Program._Configuration == null)
{
// Create the builder using a callback class
IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();
// Build everything but do not initialize it
builder.Build();
}
// Current configuration
return Program._Configuration;
}
// Update configuration
set => Program._Configuration = value;
}
#endregion
#region Public
/// <summary>
/// Start the webapp
/// </summary>
public static void Main(string[] args)
{
// Create the builder using the default Startup class
IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
// Build everything and run it
using (IWebHost host = builder.Build())
host.Run();
}
#endregion
#region CallBackConfiguration
/// <summary>
/// Aux class to callback configuration
/// </summary>
private class CallBackConfiguration
{
/// <summary>
/// Callback with configuration
/// </summary>
public CallBackConfiguration(IConfiguration configuration)
{
// Update the last configuration
Program.Configuration = configuration;
}
/// <summary>
/// Do nothing, just for compatibility
/// </summary>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//
}
}
#endregion
}
}
So now on you just use the static Program.Configuration at any other class you need it.
The error is coming because of the parser you are using. In general, if you have HTML file/code then you need to use html5lib
(documentation can be found here) & in-case you have XML file/data then you need to use lxml
(documentation can be found here). You can use lxml
for HTML file/code also but sometimes it gives an error as above. So, better to choose the package wisely based on the type of data/file. You can also use html_parser
which is built-in module. But, this also sometimes do not work.
For more details regarding when to use which package you can see the details here
The -m
switch of PuTTY takes a path to a script file as an argument, not a command.
Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m
So you have to save your command (command_run
) to a plain text file (e.g. c:\path\command.txt
) and pass that to PuTTY:
putty.exe -ssh user@host -pw password -m c:\path\command.txt
Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).
A command-line syntax is identical, an output redirection added:
plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt
See Using the command-line connection tool Plink.
And with Plink, you can actually provide the command directly on its command-line:
plink.exe -ssh user@host -pw password command > output.txt
Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file
I've recently found even more interesting way to create any ValueNode
or ContainerNode
(Jackson v2.3).
ObjectNode node = JsonNodeFactory.instance.objectNode();
I had a very strange bug. Apparently my launch image source was only set for debug configuration and not release. This resulted in my launch screen appearing when running debug configuration, but when I changed to release I just got a black screen.
I fixed this when I changed my build configuration to release the Launch Image Source button appeared and I had to choose Use Asset Catalog again.
For those who are curious, this is what my project.pbxproj looked like.
...
...
...
XXXXXXXXXXXXXXXXXXXXXXXX /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; <---THIS LINE WAS MISSING
...
...
...
// replace
return <p>hello</p>;
// with
return <p>{JSON.stringify(movies)}</p>;
Now you should see, that your code actually does work. What does not work is the console.log(movies)
. This is because movies
points to the old state. If you move your console.log(movies)
outside of useEffect
, right above the return, you will see the updated movies object.
Put log4j.properties in classpath. Here is the 2 cases that will help you to identify the proper location- 1. For web application the classpath is /WEB-INF/classes.
\WEB-INF
classes\
log4j.properties
To test from main / unit test the classpath is source directory
\Project\
src\
log4j.properties
Select "all project" and right click
Maven-> Update project
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
If I remember C++ syntax well, you can add a label to break
statements, just like for goto
. So what you want would be easily written:
while(true) {
switch(msg->state) {
case MSGTYPE: // ...
break;
// ... more stuff ...
case DONE:
break outofloop; // **HERE, I want to break out of the loop itself**
}
}
outofloop:
// rest of your code here
design
<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />
codebehind
protected void ddlArea_DataBound(object sender, EventArgs e)
{
ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}
If you'd decide for a solution acting "in place" you could take a look at this one:
>>> d = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ]
>>> [dt.update({k: int(v)}) for dt in d for k, v in dt.iteritems()]
[None, None, None, None, None, None]
>>> d
[{'a': 1, 'c': 3, 'b': 2}, {'e': 5, 'd': 4, 'f': 6}]
Btw, key order is not preserved because that's the way standard dictionaries work, ie without the concept of order.
Here's an alternative version as an Extension Method
using LINQ
.
using System;
using System.Linq;
public static class EnumExtensions
{
public static Enum GetRandomEnumValue(this Type t)
{
return Enum.GetValues(t) // get values from Type provided
.OfType<Enum>() // casts to Enum
.OrderBy(e => Guid.NewGuid()) // mess with order of results
.FirstOrDefault(); // take first item in result
}
}
public static class Program
{
public enum SomeEnum
{
One = 1,
Two = 2,
Three = 3,
Four = 4
}
public static void Main()
{
for(int i=0; i < 10; i++)
{
Console.WriteLine(typeof(SomeEnum).GetRandomEnumValue());
}
}
}
Two
One
Four
Four
Four
Three
Two
Four
One
Three
In the Environment setup, we had undefined = StrictUndefined
, which prevented undefined values from being set to anything. This fixed it:
from jinja2 import Undefined
JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }
This is a very frequent task in linux. I use grep -rn '' . all the time to do this. -r for recursive (folder and subfolders) -n so it gives the line numbers, the dot stands for the current directory.
grep -rn '<word or regex>' <location>
do a
man grep
for more options
I do think that realizing Haskell's feature by examples is the best way to start above all.
http://en.wikipedia.org/wiki/Haskell_98_features
Here is tricky typeclasses including monads and arrows
http://www.haskell.org/haskellwiki/Typeclassopedia
for real world problems and bigger project, remember these tags: GHC(most used compiler), Hackage(libraryDB), Cabal(building system), darcs(another building system).
A integrated system can save your time: http://hackage.haskell.org/platform/
the package database for this system: http://hackage.haskell.org/
GHC compiler's wiki: http://www.haskell.org/haskellwiki/GHC
After Haskell_98_features and Typeclassopedia, I think you already can find and read the documention about them yourself
By the way, you may want to test some GHC's languages extension which may be a part of haskell standard in the future.
this is my best way for learning haskell. i hope it can help you.
All the information in this thread is now out of date with the recent release of vswhere. Download that and use it.
Or if you want to count white or black pixels
This is also a solution:
from PIL import Image
import operator
img = Image.open("your_file.png").convert('1')
black, white = img.getcolors()
print black[0]
print white[0]
CREATE TABLE #tempww (
LoginName nvarchar(max),
DBname nvarchar(max),
Username nvarchar(max),
AliasName nvarchar(max)
)
INSERT INTO #tempww
EXEC master..sp_msloginmappings
-- display results
SELECT *
FROM #tempww
ORDER BY dbname, username
-- cleanup
DROP TABLE #tempww
The python 2.5 documentation explains it well.
Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is ordered first (for example, [1,2] < [1,2,3]).
Unfortunately that page seems to have disappeared in the documentation for more recent versions.
Use the PHP DOMDocument
parser.
$doc = new DOMDocument();
// load the HTML string we want to strip
$doc->loadHTML($html);
// get all the script tags
$script_tags = $doc->getElementsByTagName('script');
$length = $script_tags->length;
// for each tag, remove it from the DOM
for ($i = 0; $i < $length; $i++) {
$script_tags->item($i)->parentNode->removeChild($script_tags->item($i));
}
// get the HTML string back
$no_script_html_string = $doc->saveHTML();
This worked me me using the following HTML document:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
hey
</title>
<script>
alert("hello");
</script>
</head>
<body>
hey
</body>
</html>
Just bear in mind that the DOMDocument
parser requires PHP 5 or greater.
Using dynamic enums is bad no matter which way. You will have to go through the trouble of "duplicating" the data to ensure clear and easy code easy to maintain in the future.
If you start introducing automatic generated libraries, you are for sure causing more confusion to future developers having to upgrade your code than simply making your enum coded within the appropriate class object.
The other examples given sound nice and exciting, but think about the overhead on code maintenance versus what you get from it. Also, are those values going to change that frequently?
You can try server.connection-timeout=5000
in your application.properties. From the official documentation:
server.connection-timeout= # Time in milliseconds that connectors will wait for another HTTP request before closing the connection. When not set, the connector's container-specific default will be used. Use a value of -1 to indicate no (i.e. infinite) timeout.
On the other hand, you may want to handle timeouts on the client side using Circuit Breaker pattern as I have already described in my answer here: https://stackoverflow.com/a/44484579/2328781
git rebase -i
allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.
# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`
# switch to a new branch pointing at the first commit
git checkout -b new-root root
# make any edits and then commit them with:
git commit --amend
# check out the previous branch (i.e. master)
git checkout @{-1}
# replace old root with amended version
git rebase --onto new-root root
# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue
# delete the branch "new-root"
git branch -d new-root
# delete the tag "root"
git tag -d root
Do you create the DataTables yourself? Because iterating through the children of any Object (as in DataSet.Tables) is usually not needed, as it's the job of the Parent to dispose all its child members.
Generally, the rule is: If you created it and it implements IDisposable, Dispose it. If you did NOT create it, then do NOT dispose it, that's the job of the parent object. But each object may have special rules, check the Documentation.
For .NET 3.5, it explicitly says "Dispose it when not using anymore", so that's what I would do.
This example might help someone:
Note "origin
" is my alias for remote "What is on Github"
Note "mybranch
" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch
to show where the branch name parameter is used.
What exactly are my remote repos on github?
$ git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
Add the "other github repository of the same code" - we call this a fork:
$ git remote add someOtherRepo https://github.com/otherUser/Playground.git
$git remote -v
origin https://github.com/flipmcf/Playground.git (fetch)
origin https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)
make sure our local repo is up to date:
$ git fetch
Change some stuff locally. let's say file ./foo/bar.py
$ git status
# On branch mybranch
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# modified: foo/bar.py
Review my uncommitted changes
$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
Commit locally.
$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)
Now, I'm different than my remote (on github)
$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)
Diff this with remote - your fork:
(this is frequently done with git diff master origin
)
$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.
(git push to apply these to remote)
How does my remote branch differ from the remote master branch?
$ git diff origin/mybranch origin/master
How does my local stuff differ from the remote master branch?
$ git diff origin/master
How does my stuff differ from someone else's fork, master branch of the same repo?
$git diff mybranch someOtherRepo/master
Function pointers become easy to declare once you have the basic declarators:
ID
: ID is a*D
: D pointer toD(<parameters>)
: D function taking <
parameters>
returningWhile D is another declarator built using those same rules. In the end, somewhere, it ends with ID
(see below for an example), which is the name of the declared entity. Let's try to build a function taking a pointer to a function taking nothing and returning int, and returning a pointer to a function taking a char and returning int. With type-defs it's like this
typedef int ReturnFunction(char);
typedef int ParameterFunction(void);
ReturnFunction *f(ParameterFunction *p);
As you see, it's pretty easy to build it up using typedefs. Without typedefs, it's not hard either with the above declarator rules, applied consistently. As you see i missed out the part the pointer points to, and the thing the function returns. That's what appears at the very left of the declaration, and is not of interest: It's added at the end if one built up the declarator already. Let's do that. Building it up consistently, first wordy - showing the structure using [
and ]
:
function taking
[pointer to [function taking [void] returning [int]]]
returning
[pointer to [function taking [char] returning [int]]]
As you see, one can describe a type completely by appending declarators one after each other. Construction can be done in two ways. One is bottom-up, starting with the very right thing (leaves) and working the way through up to the identifier. The other way is top-down, starting at the identifier, working the way down to the leaves. I'll show both ways.
Construction starts with the thing at the right: The thing returned, which is the function taking char. To keep the declarators distinct, i'm going to number them:
D1(char);
Inserted the char parameter directly, since it's trivial. Adding a pointer to declarator by replacing D1
by *D2
. Note that we have to wrap parentheses around *D2
. That can be known by looking up the precedence of the *-operator
and the function-call operator ()
. Without our parentheses, the compiler would read it as *(D2(char p))
. But that would not be a plain replace of D1 by *D2
anymore, of course. Parentheses are always allowed around declarators. So you don't make anything wrong if you add too much of them, actually.
(*D2)(char);
Return type is complete! Now, let's replace D2
by the function declarator function taking <parameters>
returning, which is D3(<parameters>)
which we are at now.
(*D3(<parameters>))(char)
Note that no parentheses are needed, since we want D3
to be a function-declarator and not a pointer declarator this time. Great, only thing left is the parameters for it. The parameter is done exactly the same as we've done the return type, just with char
replaced by void
. So i'll copy it:
(*D3( (*ID1)(void)))(char)
I've replaced D2
by ID1
, since we are finished with that parameter (it's already a pointer to a function - no need for another declarator). ID1
will be the name of the parameter. Now, i told above at the end one adds the type which all those declarator modify - the one appearing at the very left of every declaration. For functions, that becomes the return type. For pointers the pointed to type etc... It's interesting when written down the type, it will appear in the opposite order, at the very right :) Anyway, substituting it yields the complete declaration. Both times int
of course.
int (*ID0(int (*ID1)(void)))(char)
I've called the identifier of the function ID0
in that example.
This starts at the identifier at the very left in the description of the type, wrapping that declarator as we walk our way through the right. Start with function taking <
parameters>
returning
ID0(<parameters>)
The next thing in the description (after "returning") was pointer to. Let's incorporate it:
*ID0(<parameters>)
Then the next thing was functon taking <
parameters>
returning. The parameter is a simple char, so we put it in right away again, since it's really trivial.
(*ID0(<parameters>))(char)
Note the parentheses we added, since we again want that the *
binds first, and then the (char)
. Otherwise it would read function taking <
parameters>
returning function .... Noes, functions returning functions aren't even allowed.
Now we just need to put <
parameters>
. I will show a short version of the deriveration, since i think you already by now have the idea how to do it.
pointer to: *ID1
... function taking void returning: (*ID1)(void)
Just put int
before the declarators like we did with bottom-up, and we are finished
int (*ID0(int (*ID1)(void)))(char)
Is bottom-up or top-down better? I'm used to bottom-up, but some people may be more comfortable with top-down. It's a matter of taste i think. Incidentally, if you apply all the operators in that declaration, you will end up getting an int:
int v = (*ID0(some_function_pointer))(some_char);
That is a nice property of declarations in C: The declaration asserts that if those operators are used in an expression using the identifier, then it yields the type on the very left. It's like that for arrays too.
Hope you liked this little tutorial! Now we can link to this when people wonder about the strange declaration syntax of functions. I tried to put as little C internals as possible. Feel free to edit/fix things in it.
This is an adaptation of the above answer, but should be more complete.
To be clear, this is to re-introduce previous auto-indent features when HTML files are open in Sublime Text. So when you finish a tag, it automatically indents for the next element.
Windows Users
Go to C:\Program Files\Sublime Text 3\Packages
extract HTML.sublime-package
as if it is a zip file to a directory.
Open Miscellaneous.tmPreferences
and copy this contents into the file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>name</key>
<string>Miscellaneous</string>
<key>scope</key>
<string>text.html</string>
<key>settings</key>
<dict>
<key>decreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>batchDecreaseIndentPattern</key>
<string>(?x)
^\s*
(</(?!html)
[A-Za-z0-9]+\b[^>]*>
|-->
|<\?(php)?\s+(else(if)?|end(if|for(each)?|while))
|\}
)</string>
<key>increaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>batchIncreaseIndentPattern</key>
<string>(?x)
^\s*
<(?!\?|area|base|br|col|frame|hr|html|img|input|link|meta|param|[^>]*/>)
([A-Za-z0-9]+)(?=\s|>)\b[^>]*>(?!.*</\1>)
|<!--(?!.*-->)
|<\?php.+?\b(if|else(?:if)?|for(?:each)?|while)\b.*:(?!.*end\1)
|\{[^}"']*$
</string>
<key>bracketIndentNextLinePattern</key>
<string><!DOCTYPE(?!.*>)</string>
</dict>
</dict>
</plist>
Then re-zip the file as HTML.sublime-package
and replace the existing HTML.sublime-package
with the one you just created.
Close and open Sublime Text 3 and you're done!
Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.
int longestRow = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].length > longestRow) {
longestRow = array[i].length;
}
}
for (int j = 0; j < longestRow; j++) {
for (int i = 0; i < array.length; i++) {
if(array[i].length > j) {
System.out.println(array[i][j]);
}
}
}
Try this.
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var json = config.Formatters.JsonFormatter;
json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }
);
}
}
Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/
However, if you want to see the mongo's admin web page, you could do it, with this command:
mongod --rest --httpinterface
browsing this url: http://localhost:28017/
the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require
Solution for Jupyter notebook PIL image visualization with arbitrary number of images:
def show(*imgs, **kwargs):
'''Show in Jupyter notebook one or sequence of PIL images in a row. figsize - optional parameter, controlling size of the image.
Examples:
show(img)
show(img1,img2,img3)
show(img1,img2,figsize=[8,8])
'''
if 'figsize' not in kwargs:
figsize = [9,9]
else:
figsize = kwargs['figsize']
fig, ax = plt.subplots(1,len(imgs),figsize=figsize)
if len(imgs)==1:
ax=[ax]
for num,img in enumerate(imgs):
ax[num].imshow(img)
ax[num].axis('off')
tight_layout()
I recommend using the awesome requests library:
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content
Take a look at the Google solution. Here is a deletion method only.
ListViewRemovalAnimation project code and Video demonstration
It needs Android 4.1+ (API 16). But we have 2014 outside.
>>> from itertools import starmap
>>> lst = [1, 2, 3]
>>> print('\n'.join(starmap('{}: {}'.format, enumerate(lst))))
0: 1
1: 2
2: 3
This uses itertools.starmap
, which is like map
, except it *
s the argument into the function. The function in this case is '{}: {}'.format
.
I would prefer the comprehension of SilentGhost, but starmap
is a nice function to know about.
EDIT: This answer is correct for version 0.2.10
. As @Alexander Vasilyev pointed out it doesn't work in version 0.2.14
.
Another reason to use $state.params
is when you need to extract query parameters like this:
$stateProvider.state('a', {
url: 'path/:id/:anotherParam/?yetAnotherParam',
controller: 'ACtrl',
});
module.controller('ACtrl', function($stateParams, $state) {
$state.params; // has id, anotherParam, and yetAnotherParam
$stateParams; // has id and anotherParam
}
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
The answers referring to simply calling array()
are not quite correct: when the buffer has been partially consumed, or is referring to a part of an array (you can ByteBuffer.wrap
an array at a given offset, not necessarily from the beginning), we have to account for that in our calculations. This is the general solution that works for buffers in all cases (does not cover encoding):
if (myByteBuffer.hasArray()) {
return new String(myByteBuffer.array(),
myByteBuffer.arrayOffset() + myByteBuffer.position(),
myByteBuffer.remaining());
} else {
final byte[] b = new byte[myByteBuffer.remaining()];
myByteBuffer.duplicate().get(b);
return new String(b);
}
For the concerns related to encoding, see Andy Thomas' answer.
If you came across the error when tried to generate a jks file (keystore), so try adding
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool
before running the command, like so:
/Applications/Android\ Studio.app/Contents/jre/jdk/Contents/Home/bin/keytool -genkey -v -keystore ~/key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias key
Try this query -
SELECT
t2.company_name,
t2.expose_new,
t2.expose_used,
t1.title,
t1.seller,
t1.status,
CASE status
WHEN 'New' THEN t2.expose_new
WHEN 'Used' THEN t2.expose_used
ELSE NULL
END as 'expose'
FROM
`products` t1
JOIN manufacturers t2
ON
t2.id = t1.seller
WHERE
t1.seller = 4238
You gave a condition ID (>79 and < 296) then the answer is:
delete from tab
where id > 79 and id < 296
this is the same as:
delete from tab
where id between 80 and 295
if id
is an integer.
All answered:
delete from tab
where id between 79 and 296
this is the same as:
delete from tab
where id => 79 and id <= 296
Mind the difference.
Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.
I'm using the awesome_print gem
So you just have to type :
ap @var
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName
won't be Netscape
. Does Chrome support document.all
? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape
branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name
attribute on the input
elements, so they won't be added to the form's elements
array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements
array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById
support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
What you want is org.mockito.Mockito.CALLS_REAL_METHODS
according to the docs:
/**
* Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation can be helpful when working with legacy code.
* When this implementation is used, unstubbed methods will delegate to the real implementation.
* This is a way to create a partial mock object that calls real methods by default.
* <p>
* As usual you are going to read <b>the partial mock warning</b>:
* Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
* How does partial mock fit into this paradigm? Well, it just doesn't...
* Partial mock usually means that the complexity has been moved to a different method on the same object.
* In most cases, this is not the way you want to design your application.
* <p>
* However, there are rare cases when partial mocks come handy:
* dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
* However, I wouldn't use partial mocks for new, test-driven & well-designed code.
* <p>
* Example:
* <pre class="code"><code class="java">
* Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
*
* // this calls the real implementation of Foo.getSomething()
* value = mock.getSomething();
*
* when(mock.getSomething()).thenReturn(fakeValue);
*
* // now fakeValue is returned
* value = mock.getSomething();
* </code></pre>
*/
Thus your code should look like:
import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
public class StockTest {
public class Stock {
private final double price;
private final int quantity;
Stock(double price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public double getValue() {
return getPrice() * getQuantity();
}
}
@Test
public void getValueTest() {
Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
when(stock.getPrice()).thenReturn(100.00);
when(stock.getQuantity()).thenReturn(200);
double value = stock.getValue();
assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
}
}
The call to Stock stock = mock(Stock.class);
calls org.mockito.Mockito.mock(Class<T>)
which looks like this:
public static <T> T mock(Class<T> classToMock) {
return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}
The docs of the value RETURNS_DEFAULTS
tell:
/**
* The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
* Typically it just returns some empty value.
* <p>
* {@link Answer} can be used to define the return values of unstubbed invocations.
* <p>
* This implementation first tries the global configuration.
* If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
*/
In your css add a class:
.fa-clickable {
cursor:pointer;
outline:none;
}
Then add the class to the clickable fontawesome icons (also an id so you can differentiate the clicks):
<i class="fa fa-dribbble fa-4x fa-clickable" id="epd-dribble"></i>
<i class="fa fa-behance-square fa-4x fa-clickable" id="epd-behance"></i>
<i class="fa fa-linkedin-square fa-4x fa-clickable" id="epd-linkedin"></i>
<i class="fa fa-twitter-square fa-4x fa-clickable" id="epd-twitter"></i>
<i class="fa fa-facebook-square fa-4x fa-clickable" id="epd-facebook"></i>
Then add a handler in your jQuery
$(document).on("click", "i", function(){
switch (this.id) {
case "epd-dribble":
// do stuff
break;
// add additional cases
}
});
Here is the solution for Rest API
class Program
{
static void Main(string[] args)
{
BaseClient clientbase = new BaseClient("https://website.com/api/v2/", "username", "password");
BaseResponse response = new BaseResponse();
BaseResponse response = clientbase.GetCallV2Async("Candidate").Result;
}
public async Task<BaseResponse> GetCallAsync(string endpoint)
{
try
{
HttpResponseMessage response = await client.GetAsync(endpoint + "/").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
else
{
baseresponse.ResponseMessage = await response.Content.ReadAsStringAsync();
baseresponse.StatusCode = (int)response.StatusCode;
}
return baseresponse;
}
catch (Exception ex)
{
baseresponse.StatusCode = 0;
baseresponse.ResponseMessage = (ex.Message ?? ex.InnerException.ToString());
}
return baseresponse;
}
}
public class BaseResponse
{
public int StatusCode { get; set; }
public string ResponseMessage { get; set; }
}
public class BaseClient
{
readonly HttpClient client;
readonly BaseResponse baseresponse;
public BaseClient(string baseAddress, string username, string password)
{
HttpClientHandler handler = new HttpClientHandler()
{
Proxy = new WebProxy("http://127.0.0.1:8888"),
UseProxy = false,
};
client = new HttpClient(handler);
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var byteArray = Encoding.ASCII.GetBytes(username + ":" + password);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
baseresponse = new BaseResponse();
}
}
MD5 also benefits from SSE2 usage, check out BarsWF and then tell me that it doesn't. All it takes is a little assembler knowledge and you can craft your own MD5 SSE2 routine(s). For large amounts of throughput however, there is a tradeoff of the speed during hashing as opposed to the time spent rearranging the input data to be compatible with the SIMD instructions used.
You might want a variant of exists ... perldoc -f "-f"
-X FILEHANDLE
-X EXPR
-X DIRHANDLE
-X A file test, where X is one of the letters listed below. This unary operator takes one argument,
either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is
true about it. If the argument is omitted, tests $_, except for "-t", which tests STDIN. Unless
otherwise documented, it returns 1 for true and '' for false, or the undefined value if the file
doesn’t exist. Despite the funny names, precedence is the same as any other named unary operator.
The operator may be any of:
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
-x File is executable by effective uid/gid.
-o File is owned by effective uid.
-R File is readable by real uid/gid.
-W File is writable by real uid/gid.
-X File is executable by real uid/gid.
-O File is owned by real uid.
-e File exists.
-z File has zero size (is empty).
-s File has nonzero size (returns size in bytes).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO), or Filehandle is a pipe.
-S File is a socket.
-b File is a block special file.
-c File is a character special file.
-t Filehandle is opened to a tty.
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.
-T File is an ASCII text file (heuristic guess).
-B File is a "binary" file (opposite of -T).
-M Script start time minus file modification time, in days.
...any reason why you can't use min()
?
def above(my_list, minimum):
if min(my_list) >= minimum:
print "All values are equal or above", minimum
else:
print "Not all values are equal or above", minimum
I don't know if this is exactly what you want, but technically, this is what you asked for...
If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce
Usage:
<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />
Then in your component:
<script>
export default {
name: 'example',
data () {
return {
delay: 1000,
term: '',
}
},
watch: {
term () {
// Do something with search term after it debounced
console.log(`Search term changed to ${this.term}`)
}
},
directives: {
debounce
}
}
</script>
The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe
:
C:\Program Files\Support Tools>setx /?
SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.
1) Command Line Mode: setx variable value [-m]
Optional Switches:
-m Set value in the Machine environment. Default is User.
...
For more information and example use: SETX -i
I think Windows 7 actually comes with setx
as part of a standard install.
docker-compose down --rmi all
and then restart your computer
You could also import all operators this way:
import {Observable} from 'rxjs/Rx';
Besides len
you can also use operator.length_hint
(requires Python 3.4+). For a normal list
both are equivalent, but length_hint
makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:
>>> from operator import length_hint
>>> l = ["apple", "orange", "banana"]
>>> len(l)
3
>>> length_hint(l)
3
>>> list_iterator = iter(l)
>>> len(list_iterator)
TypeError: object of type 'list_iterator' has no len()
>>> length_hint(list_iterator)
3
But length_hint
is by definition only a "hint", so most of the time len
is better.
I've seen several answers suggesting accessing __len__
. This is all right when dealing with built-in classes like list
, but it could lead to problems with custom classes, because len
(and length_hint
) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize
value). So it's always safer to use the len
function instead of the __len__
method!
I just created a subclass of UILabel to specially address such use cases. You can add multiple links easily and define different handlers for them. It also supports highlighting the pressed link when you touch down for touch feedback. Please refer to https://github.com/null09264/FRHyperLabel.
In your case, the code may like this:
FRHyperLabel *label = [FRHyperLabel new];
NSString *string = @"This morph was generated with Face Dancer, Click to view in the app store.";
NSDictionary *attributes = @{NSFontAttributeName: [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]};
label.attributedText = [[NSAttributedString alloc]initWithString:string attributes:attributes];
[label setLinkForSubstring:@"Face Dancer" withLinkHandler:^(FRHyperLabel *label, NSString *substring){
[[UIApplication sharedApplication] openURL:aURL];
}];
Sample Screenshot (the handler is set to pop an alert instead of open a url in this case)
Check out this snippet:
Private Sub openDialog()
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file."
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls"
.Filters.Add "All Files", "*.*"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
End Sub
I think this is what you are asking for.
pgrep -f youAppFile.py | xargs kill -9
pgrep
returns the PID of the specific file will only kill the specific application.
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
Training set: A set of examples used for learning, that is to fit the parameters [i.e., weights] of the classifier.
Validation set: A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.
Test set: A set of examples used only to assess the performance [generalization] of a fully specified classifier.
From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"
The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.
The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.
Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.
EDIT:
Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
You can tweak the string to split by - if you use "code : "
, the second member of the returned array ([1]
) will contain "-1"
, using your example.
This is the way I did it:
I just put
Intent intent = new Intent(Main.this, SOMECLASSNAME.class);
Main.this.startActivityForResult(intent, 0);
inside of the method that opens an activity, then inside of the method of SOMECLASSNAME that is designed to close the app I put:
setResult(0);
finish();
And I put the following in my Main class:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == 0) {
finish();
}
}
$(".excel").click(function () {
var t = $(this).closest(".tblGrid").attr("id");
window.frames["Iframe" + t].document.location.href = pagename + "?tbl=" + t;
});
this is what i use, no jquery needed for this. in this particular scenario for each table i have with an excel export icon this forces the iframe attached to that table to load the same page with a variable in the Query String that the page looks for, and if found response writes out a stream with an excel mimetype and includes the data for that table.
If you are working with PyCharm, I found that restarting the program and closing all prompts after adding 'rest_framework' to my INSTALLED_APPS
worked for me.
all depend on the configuration. for me works
comboBox.SelectedIndex = -1;
my configuration
DropDownStyle: DropDownList
(text can't be changed for the user)
Just searched for the docs, and found this:
Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:
{# returns true #}
{{ 1 in [1, 2, 3] }}
{{ 'cd' in 'abcde' }}
The accepted answer did not work for me. Here's what I'm doing to pull a package from github:
npm install --save "git://github.com/username/package.git#commit"
Or adding it manually on package.json:
"dependencies": {
"package": "git://github.com/username/package.git#commit"
}
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
If you changed height of tableView's headerView, just reset headerView's frame, then, reset headerView of tableView:
self.headerView.frame = newFrame;
self.tableView.tableHeaderView = self.headerView;
There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)
You can also use a background image replacement as an alternative, giving you total control over vertical and horizontal positioning.
See the answer to this Question
It's not about performance. It's about what makes a good primary key. Unique and unchanging over time. You may think an entity such as a country code never changes over time and would be a good candidate for a primary key. But bitter experience is that is seldom so.
INT AUTO_INCREMENT meets the "unique and unchanging over time" condition. Hence the preference.
You can paste it like this:
= "2010-12-20" - 180
And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab
Always use the window.addEventListener
to add an event to window. Because that way you can execute the code in different event handlers .
Correct code:
window.addEventListener('load', function () {_x000D_
alert('Hello!')_x000D_
})_x000D_
_x000D_
window.addEventListener('load', function () {_x000D_
alert('Bye!')_x000D_
})
_x000D_
Invalid code:
window.onload = function () {_x000D_
alert('Hello!') // it will not work!!!_x000D_
}_x000D_
_x000D_
window.onload = function () {_x000D_
alert('Bye!') _x000D_
}
_x000D_
This is because onload is just property of the object, which is overwritten.
By analogy with addEventListener
, it is better to use $(document).ready()
rather than onload.
On Linux man ascii
says:
ASCII is the American Standard Code for Information Interchange. It is a 7-bit code.
There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html
I use the following method to execute commands on a password protected client:
import paramiko
nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username'
password = 'password'
command = 'ls'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
if session.recv_ready():
stdout_data.append(session.recv(nbytes))
if session.recv_stderr_ready():
stderr_data.append(session.recv_stderr(nbytes))
if session.exit_status_ready():
break
print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)
session.close()
client.close()
Another way is with Arrays.setAll
, or Arrays.fill
:
String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]
Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]
This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
Use -a
(for and) and -o
(for or) operations.
tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html
Update
Actually you could still use &&
and ||
with the -eq
operation. So your script would be like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ] || ([ $my_error_flag -eq 1 ] && [ $my_error_flag_o -eq 2 ]); then
echo "$my_error_flag"
else
echo "no flag"
fi
Although in your case you can discard the last two expressions and just stick with one or operation like this:
my_error_flag=1
my_error_flag_o=1
if [ $my_error_flag -eq 1 ] || [ $my_error_flag_o -eq 2 ]; then
echo "$my_error_flag"
else
echo "no flag"
fi
It is called Telescoping Constructor anti-pattern or constructor chaining. Yes, you can definitely do. I see many examples above and I want to add by saying that if you know that you need only two or three constructor, it might be ok. But if you need more, please try to use different design pattern like Builder pattern. As for example:
public Omar(){};
public Omar(a){};
public Omar(a,b){};
public Omar(a,b,c){};
public Omar(a,b,c,d){};
...
You may need more. Builder pattern would be a great solution in this case. Here is an article, it might be helpful https://medium.com/@modestofiguereo/design-patterns-2-the-builder-pattern-and-the-telescoping-constructor-anti-pattern-60a33de7522e
I used
getContext().getApplicationContext().getString(R.string.nameOfString);
It works for me.
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
Functionally, you use public/private key encryption to make certain only the receiver can read your message. The message is encrypted using the public key of the receiver and decrypted using the private key of the receiver.
Signing you can use to let the receiver know you created the message and it has not changed during transfer. Message signing is done using your own private key. The receiver can use your public key to check the message has not been tampered.
As for the algorithm used: that involves a one-way function see for example wikipedia. One of the first of such algorithms use large prime-numbers but more one-way functions have been invented since.
Search for 'Bob', 'Alice' and 'Mallory' to find introduction articles on the internet.
I had the same question but applying the provided solutions changed the file to write in. Once I selected the new excel file, I was also writing in that file and not in my original file. My solution for this issue is below:
Sub GetData()
Dim excelapp As Application
Dim source As Workbook
Dim srcSH1 As Worksheet
Dim sh As Worksheet
Dim path As String
Dim nmr As Long
Dim i As Long
nmr = 20
Set excelapp = New Application
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
.Show
path = .SelectedItems.Item(1)
End With
Set source = excelapp.Workbooks.Open(path)
Set srcSH1 = source.Worksheets("Sheet1")
Set sh = Sheets("Sheet1")
For i = 1 To nmr
sh.Cells(i, "A").Value = srcSH1.Cells(i, "A").Value
Next i
End Sub
With excelapp
a new application will be called. The with
block sets the path for the external file. Finally, I set the external Workbook with source
and srcSH1
as a Worksheet within the external sheet.
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
Can be done with pure Bootstrap code.
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="form-group">_x000D_
<label for="id" class="col-md-2 control-label">ID</label>_x000D_
<div class="input-group">_x000D_
<span class="input-group-btn">_x000D_
<select class="form-control" name="id" id="id">_x000D_
<option value="">_x000D_
</select>_x000D_
</span>_x000D_
<span class="input-group-btn">_x000D_
<select class="form-control" name="nr" id="nr">_x000D_
<option value="">_x000D_
</select>_x000D_
</span>_x000D_
</div> _x000D_
</div>
_x000D_
There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.
Use Heredocs to output muli-line strings containing variables. The syntax is...
$string = <<<HEREDOC
string stuff here
HEREDOC;
The "HEREDOC" part is like the quotes, and can be anything you want. The end tag must be the only thing on it's line i.e. no whitespace before or after, and must end in a colon. For more info check out the manual.
Here is another fix:
My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.
I had the same issue, so tried a few things. One of which seemed to work for me - removing the width and adding a float to the body tag.
May not work for all instances, but in the scenario I recently had, hiding overflow on content elements was a no go...
For posterity, fish aliases are just functions:
$ alias foo="echo bar"
$ type foo
foo is a function with definition
function foo
echo bar $argv;
end
To remove it
$ unalias foo
/usr/bin/unalias: line 2: unalias: foo: not found
$ functions -e foo
$ type foo
type: Could not find “foo”
Your specific error is with line 11:
awk 'BEGIN{sum+=$2}'
This is a line where awk
is invoked, and its BEGIN
block is specified - but you are already within a awk script, so you do not need to specify awk
. Also you want to run sum+=$2
on each line of input, so you do not want it within a BEGIN
block. Hence the line should simply read:
sum+=$2
You also do not need the lines:
x=sum
read name
the first just creates a synonym to sum
named x
and I'm not sure what the second does, but neither are needed.
This would make your awk script:
#!/bin/awk
### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.
# This block of code is executed for each line in the file
{
sum+=$2
# The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
# NR is a variable equal to the number of rows in the file
print "Average: " sum/ NR
# Change this to print the Average instead of just the number of rows
}
Jonathan Leffler's answer gives the awk one liner which represents the same fixed code, with the addition of checking that there are at least 1 lines of input (this stops any divide by zero error). If
No, anonymous types cannot implement an interface. From the C# programming guide:
Anonymous types are class types that consist of one or more public read-only properties. No other kinds of class members such as methods or events are allowed. An anonymous type cannot be cast to any interface or type except for object.
I would like to add my answer to the table and here it is :
//connect to db ...etc
$result_product = /*your mysql query here*/
$array_product = array();
$i = 0;
foreach ($result_product as $row_product)
{
$array_product [$i]["id"]= $row_product->id;
$array_product [$i]["name"]= $row_product->name;
$i++;
}
//you can encode the array to json if you want to send it to an ajax call
$json_product = json_encode($array_product);
echo($json_product);
hope that this will help somebody
You can find an example and the technical reason to why it is not allowed in @stefan 's answer. Now a logical answer to this question according to me is:
The major use of virtual keyword is to enable polymorphic behaviour when we don't know what type of the object the base class pointer will point to.
But think of this is more primitive way, for using virtual functionality you will require a pointer. And what does a pointer require? An object to point to! (considering case for correct execution of the program)
So, we basically require an object that already exists somewhere in the memory (we are not concerned with how the memory was allocated, it may be at compile time or either runtime) so that our pointer can correctly point to that object.
Now, think of the situation about the moment when the object of the class to be pointed is being assigned some memory -> Its constructor will be called automatically at that instance itself!
So we can see that we don't actually need to worry about the constructor being virtual, because in any of the cases you wish to use a polymorphic behaviour our constructor would have already been executed making our object ready for usage!
Request.QueryString
helps you to get the parameters
and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
For only pick from local add this :
i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
And this working nice :
val i = Intent(Intent.ACTION_GET_CONTENT,MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
i.type = "image/*"
i.putExtra(Intent.EXTRA_LOCAL_ONLY,true)
startActivityForResult(Intent.createChooser(i,"Select Photo"),pickImageRequestCode)
<input type="file"
id="fileUploadButton"
style={{ display: 'none' }}
onChange={onFileChange}
/>
<label htmlFor={'fileUploadButton'}>
<Button
color="secondary"
className={classes.btnUpload}
variant="contained"
component="span"
startIcon={
<SvgIcon fontSize="small">
<UploadIcon />
</SvgIcon>
}
>
Upload
</Button>
</label>
Make sure Button has component="span", that helped me.
If you need only make and friends. Try installing the command-line-tools provided by Apple. (Assuming you are not doing any iOS development.)
Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:
rem The retail files set
set FILES_SET="(*.exe *.dll"
rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"
rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%
rem Append the closing bracket
set FILES_SET=%FILES_SET%)
echo %FILES_SET%
Cheers...
You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-
(untested code)
Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")
' now you can manipulate the data in the workbook anyway you want, e.g. '
Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value
Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False
' etc '
Call wbk.Close(False)
Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.
Delegate and Live are easy to use but if you won't have any more li:s added dynamically you could use event delagation with normal bind/click as well. There should be some performance gain using this method since the DOM won't have to be monitored for new matching elements. Haven't got any actual numbers but it makes sense :)
$("#wizard").click(function (e) {
var source = $(e.target);
if(source.is("li")){
// alert index of li relative to ul parent
alert(source.index());
}
});
You could test it at jsFiddle: http://jsfiddle.net/jimmysv/4Sfdh/1/
If you are on Teradata, then Teradata Developer Exchange has a detailed article on loading and retrieving lobs and blobs..
http://developer.teradata.com/applications/articles/large-objects-part-1-loading
int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000
You can use hibernate lazy initializer.
Below is the code you can refer.
Here PPIDO
is the data object which I want to retrieve
Hibernate.initialize(ppiDO);
if (ppiDO instanceof HibernateProxy) {
ppiDO = (PolicyProductInsuredDO) ((HibernateProxy) ppiDO).getHibernateLazyInitializer()
.getImplementation();
ppiDO.setParentGuidObj(policyDO.getBasePlan());
saveppiDO.add(ppiDO);
proxyFl = true;
}
If you are using moment then you can use their "official plugin" for ranges moment-range
and then this becomes trivial.
moment-range node example:
const Moment = require('moment');
const MomentRange = require('moment-range');
const moment = MomentRange.extendMoment(Moment);
const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));
console.log(Array.from(range.by('day')))
moment-range browser example:
window['moment-range'].extendMoment(moment);_x000D_
_x000D_
const start = new Date("11/30/2018"), end = new Date("09/30/2019")_x000D_
const range = moment.range(moment(start), moment(end));_x000D_
_x000D_
console.log(Array.from(range.by('day')))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>
_x000D_
date fns example:
If you are using date-fns
then eachDay
is your friend and you get by far the shortest and most concise answer:
console.log(dateFns.eachDay(_x000D_
new Date(2018, 11, 30),_x000D_
new Date(2019, 30, 09)_x000D_
))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
_x000D_
It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.
While, this is not technically what you want, if you know before hand the type of object you want to handle you can use the call/apply methods of the prototype of your known object.
you can change this
alert(fooJSON.test() ); //Prints 12
to this
alert(Foo.prototype.test.call(fooJSON); //Prints 12
I was totally lost on why my Gridview.Databind()
would not refresh.
My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:
gvServerConfiguration.Databind()
uppServerConfiguration.Update()
uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.
Hope this helps someone.
Would this help?
tail -f access.log | stdbuf -oL cut -d ' ' -f1 | uniq
This will immediately display unique entries from access.log using the stdbuf utility.
Use git add -A
, this will include the deleted files.
Note: use git rm
for certain files.
Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate
Run the process with .Exec
.
Then wait for 4 seconds.
After that kill this process.
You don't need cURL to do POSTed form data. --post-data 'key1=value1&key2=value2'
works just fine. Note: you can also pass a file name to wget with the POST data in the file.
new[,2]
is a factor, not a numeric vector. Transform it first
new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5
$(".oSlider-rotate").slider({
min: 10,
max: 74,
step: .01,
value: 24,
slide: function(e,ui){
$('.user-text').css('transform', 'scale(' + ui.value + ')')
}
});
This will solve the issue
Maybe things changed, but I recall rapleaf had a service where you enter an email address and you could receive a facebook id.
https://www.rapleaf.com/
If something was not in there, one could "sign up" with the email, and it should have a chance to get the data after a while.
I came across this when using a search tool called Maltego a few years back.
The app uses many types of "transforms", and a few where related to facebook and twitter etc..
..or find some new sqli's on fb and fb apps, hehe. :)
Use this regular expression to match ten digits only:
@"^\d{10}$"
To find a sequence of ten consecutive digits anywhere in a string, use:
@"\d{10}"
Note that this will also find the first 10 digits of an 11 digit number. To search anywhere in the string for exactly 10 consecutive digits and not more you can use negative lookarounds:
@"(?<!\d)\d{10}(?!\d)"
<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
<TR style="vertical-align:top">
<TD>
<!-- The log text-box -->
<div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
Log:
</div>
</TD>
<TD>
<!-- The 2nd column -->
</TD>
<TD>
<!-- The 3rd column -->
</TD>
</TR>
</TABLE>
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
yes you can
DataGridView1.Rows[0].HeaderCell.Value = "my text";
On Linux, add --add-host=host.docker.internal:host-gateway
to your Docker command to enable this feature. (See below for Docker Compose configuration.)
Use your internal IP address or connect to the special DNS name host.docker.internal
which will resolve to the internal IP address used by the host.
To enable this in Docker Compose on Linux, add the following lines to the container definition:
extra_hosts: - "host.docker.internal:host-gateway"
Use your internal IP address or connect to the special DNS name host.docker.internal
which will resolve to the internal IP address used by the host.
Linux support pending https://github.com/docker/for-linux/issues/264
Same as above but use docker.for.mac.host.internal
instead.
Same as above but use docker.for.mac.localhost
instead.
To access host machine from the docker container you must attach an IP alias to your network interface. You can bind whichever IP you want, just make sure you're not using it to anything else.
sudo ifconfig lo0 alias 123.123.123.123/24
Then make sure that you server is listening to the IP mentioned above or 0.0.0.0
. If it's listening on localhost 127.0.0.1
it will not accept the connection.
Then just point your docker container to this IP and you can access the host machine!
To test you can run something like curl -X GET 123.123.123.123:3000
inside the container.
The alias will reset on every reboot so create a start-up script if necessary.
Solution and more documentation here: https://docs.docker.com/docker-for-mac/networking/#use-cases-and-workarounds
if you found out that the memory settings were not being used and in order to change the memory settings, I used the tomcat7w or tomcat8w in the \bin folder.Then the following should pop up:
Click the Java tab and add the arguments.restart tomcat
Available as standard in Java 7, path.copyTo: http://openjdk.java.net/projects/nio/javadoc/java/nio/file/Path.html http://java.sun.com/docs/books/tutorial/essential/io/copy.html
I can't believe it took them so long to standardise something so common and simple as file copying :(
i fell into a case where clearing the entire array failed with dim/redim :
having 2 module-wide arrays, Private inside a userform,
One array is dynamic and uses a class module, the other is fixed and has a special type.
Option Explicit
Private Type Perso_Type
Nom As String
PV As Single 'Long 'max 1
Mana As Single 'Long
Classe1 As String
XP1 As Single
Classe2 As String
XP2 As Single
Classe3 As String
XP3 As Single
Classe4 As String
XP4 As Single
Buff(1 To 10) As IPicture 'Disp
BuffType(1 To 10) As String
Dances(1 To 10) As IPicture 'Disp
DancesType(1 To 10) As String
End Type
Private Data_Perso(1 To 9, 1 To 8) As Perso_Type
Dim ImgArray() As New ClsImage 'ClsImage is a Class module
And i have a sub declared as public to clear those arrays (and associated run-time created controls) from inside and outside the userform like this :
Public Sub EraseControlsCreatedAtRunTime()
Dim i As Long
On Error Resume Next
With Me.Controls 'removing all on run-time created controls of the Userform :
For i = .Count - 1 To 0 Step -1
.Remove i
Next i
End With
Err.Clear: On Error GoTo 0
Erase ImgArray, Data_Perso
'ReDim ImgArray() As ClsImage ' i tried this, no error but wouldn't work correctly
'ReDim Data_Perso(1 To 9, 1 To 8) As Perso_Type 'without the erase not working, with erase this line is not needed.
End Sub
note : this last sub was first called from outside (other form and class module) with Call FormName.SubName
but had to replace it with Application.Run FormName.SubName
, less errors, don't ask why...
Please use this.. it is simplest.
\p{Punct} Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
StringBuilder builder = new StringBuilder(checkstring);
String regex = "\\p{Punct}"; //Special character : `~!@#$%^&*()-_+=\|}{]["';:/?.,><
//change your all special characters to ""
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(builder.toString());
checkstring=matcher.replaceAll("");
Suppose we haven't used the "@" operator then our code would look like this:
$fileHandle = fopen($fileName, $writeAttributes);
And what if the file we are trying to open is not found? It will show an error message.
To suppress the error message we are using the "@" operator like:
$fileHandle = @fopen($fileName, $writeAttributes);
Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});
This is what you want:
@page {
@bottom-right {
content: counter(page) " of " counter(pages);
}
}
I took the liberty of modifying ConorLuddy's answer to address both 24 hour time and 12 hour time.
function minutesToHHMM (mins, twentyFour = false) {
let h = Math.floor(mins / 60);
let m = mins % 60;
m = m < 10 ? '0' + m : m;
if (twentyFour) {
h = h < 10 ? '0' + h : h;
return `${h}:${m}`;
} else {
let a = 'am';
if (h >= 12) a = 'pm';
if (h > 12) h = h - 12;
return `${h}:${m} ${a}`;
}
}
I recommend PyInstaller, a simple python script can be converted to an exe with the following commands:
utils/Makespec.py [--onefile] oldlogs.py
which creates a yourprogram.spec file which is a configuration for building the final exe. Next command builds the exe from the configuration file:
utils/Build.py oldlogs.spec
More can be found here
One simple approach you could take is to compare the length of the original string with that of the string to have whitespaces replaced with nothing. For example:
function hasWhiteSpaces(string) {
if (string.length == string.replace(" ", "").length) {return false}
return true
}
You can simply subtract two dates. You have to cast it first, using to_date
:
select to_date('2000-01-01', 'yyyy-MM-dd')
- to_date('2000-01-02', 'yyyy-MM-dd')
datediff
from dual
;
The result is in days, to the difference of these two dates is -1
(you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.
I recently felt like I had to do this too, but then found another way which possibly makes my code look neater, and uses better OOP.
I have many sibling classes that each implement a certain method doSomething()
. In order to access that method, I would have to have an instance of that class first, but I created a superclass for all my sibling classes and now I can access the method from the superclass.
Below I show two ways alternative ways to "dynamic casting".
// Method 1.
mFragment = getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
switch (mUnitNum) {
case 0:
((MyFragment0) mFragment).sortNames(sortOptionNum);
break;
case 1:
((MyFragment1) mFragment).sortNames(sortOptionNum);
break;
case 2:
((MyFragment2) mFragment).sortNames(sortOptionNum);
break;
}
and my currently used method,
// Method 2.
mSuperFragment = (MySuperFragment) getFragmentManager().findFragmentByTag(MyHelper.getName(mUnitNum));
mSuperFragment.sortNames(sortOptionNum);
I'd like to add one more thing. In LINQ to SQL if your DB is properly built and your tables are related through foreign key constraints, then you do not need to do a join at all.
Using LINQPad I created the following LINQ query:
//Querying from both the CustomerInfo table and OrderInfo table
from cust in CustomerInfo
where cust.CustomerID == 123456
select new {cust, cust.OrderInfo}
Which was translated to the (slightly truncated) query below
-- Region Parameters
DECLARE @p0 Int = 123456
-- EndRegion
SELECT [t0].[CustomerID], [t0].[AlternateCustomerID], [t1].[OrderID], [t1].[OnlineOrderID], (
SELECT COUNT(*)
FROM [OrderInfo] AS [t2]
WHERE [t2].[CustomerID] = [t0].[CustomerID]
) AS [value]
FROM [CustomerInfo] AS [t0]
LEFT OUTER JOIN [OrderInfo] AS [t1] ON [t1].[CustomerID] = [t0].[CustomerID]
WHERE [t0].[CustomerID] = @p0
ORDER BY [t0].[CustomerID], [t1].[OrderID]
Notice the LEFT OUTER JOIN
above.
I use div instead of tables and am able to target classes within the main class, as below:
.main {
.width: 800px;
.margin: 0 auto;
.text-align: center;
}
.main .table {
width: 80%;
}
.main .row {
/ ***something ***/
}
.main .column {
font-size: 14px;
display: inline-block;
}
.main .left {
width: 140px;
margin-right: 5px;
font-size: 12px;
}
.main .right {
width: auto;
margin-right: 20px;
color: #fff;
font-size: 13px;
font-weight: normal;
}
<div class="main">
<div class="table">
<div class="row">
<div class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
If you want to style a particular "cell" exclusively you can use another sub-class or the id of the div e.g:
.main #red { color: red; }
<div class="main">
<div class="table">
<div class="row">
<div id="red" class="column left">Swing Over Bed</div>
<div class="column right">650mm</div>
<div class="column left">Swing In Gap</div>
<div class="column right">800mm</div>
</div>
</div>
</div>
Answer is to add a having clause:
SELECT [columns]
FROM table t1
WHERE value= (select max(value) from table)
AND date = (select MIN(date) from table t2 where t1.value = t2.value)
this should work and gets rid of the neccesity of having an extra sub select in the date clause.
You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
Solution with initialization subscriber directly in event function:
import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
class MyAppComponent {
searchTermChanged: Subject<string> = new Subject<string>();
constructor() {
}
onFind(event: any) {
if (this.searchTermChanged.observers.length === 0) {
this.searchTermChanged.pipe(debounceTime(1000), distinctUntilChanged())
.subscribe(term => {
// your code here
console.log(term);
});
}
this.searchTermChanged.next(event);
}
}
And html:
<input type="text" (input)="onFind($event.target.value)">
Just wanted to point out something about the solution said above several times:
git config credential.helper store
You can use any command that requires a password after this. You don't have to push. (you can also pull for instance) After that, you won't need to type in your username / password again.
Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.
The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.
Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,
using Microsoft.AspNet.Identity;
int userId = User.Identity.GetUserId<int>();
will do the trick
You could put the text into a div (or other container) with a width of 50%.
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
You can change the CHARSET and COLLATION of all your tables through PHP script as follows. I like the answer of hkasera but the problem with it is that the query runs twice on each table. This code is almost the same except using MySqli instead of mysql and prevention of double querying. If I could vote up, I would have voted hkasera's answer up.
<?php
$conn1=new MySQLi("localhost","user","password","database");
if($conn1->connect_errno){
echo mysqli_connect_error();
exit;
}
$res=$conn1->query("show tables") or die($conn1->error);
while($tables=$res->fetch_array()){
$conn1->query("ALTER TABLE $tables[0] CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") or die($conn1->error);
}
echo "The collation of your database has been successfully changed!";
$res->free();
$conn1->close();
?>
You can add any extension (in Wamp and Xampp servers) by removing the semi-colon (;)
Console.WriteLine(curr.ToString("HH:mm"));
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
you need nested foreach loops
foreach($samplearr as $key => $item){
echo $key;
foreach($item as $detail){
echo $detail['value1'] . " " . $detail['value2']
}
}
Absolutely Asset Catalog is you answer, it removes the need to follow naming conventions when you are adding or updating your app icons.
Below are the steps to Migrating an App Icon Set or Launch Image Set From Apple:
1- In the project navigator, select your target.
2- Select the General pane, and scroll to the App Icons section.
3- Specify an image in the App Icon table by clicking the folder icon on the right side of the image row and selecting the image file in the dialog that appears.
4-Migrate the images in the App Icon table to an asset catalog by clicking the Use Asset Catalog button, selecting an asset catalog from the popup menu, and clicking the Migrate button.
Alternatively, you can create an empty app icon set by choosing Editor > New App Icon, and add images to the set by dragging them from the Finder or by choosing Editor > Import.
I was getting the same error today:
Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.
What I did:
27.1.1
instead of 26.1.0
compileSdkVersion 27
and targetSdkVersion 27
which were 26
earlierAnd com.android.support:support-annotations
error was gone!
For Ref:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
You should use the built in line separator. The advantage is that you don't have to concern what system you code is running on, it will just work.
Since Java 1.7
System.lineSeparator()
Pre Java 1.7
System.getProperty("line.separator")
Edit 2020
Referring back to the (closed) github issue, where it is pointed out, there is no actual session or state;
docker login actually isn't creating any sort of persistent session, it is only storing the user's credentials on disk so that when authentication is required it can read them to login
As others have pointed out, an auths
entry/node is added to the ~/.docker/config.json
file (this also works for private registries) after you succesfully login:
{
"auths": {
"https://index.docker.io/v1/": {}
},
...
When logging out, this entry is then removed:
$ docker logout
Removing login credentials for https://index.docker.io/v1/
Content of docker config.json
after:
{
"auths": {},
...
This file can be parsed by your script or code to check your login status.
You can login to docker with docker login <repository>
$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If
you don't have a Docker ID, head over to https://hub.docker.com to
create one.
Username:
If you are already logged in, the prompt will look like:
$ docker login
Login with your Docker ID to push and pull images from Docker Hub. If
you don't have a Docker ID, head over to https://hub.docker.com to
create one.
Username (myusername): # <-- "myusername"
For the original explanation for the ~/.docker/config.json
, check question: how can I tell if I'm logged into a private docker registry
Here is my way:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
rm /usr/local/var/postgres/postmaster.pid
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
There is no such method as slideLeft() and slideRight() which looks like slideUp() and slideDown(), but you can simulate these effects using jQuery’s animate() function.
HTML Code:
<div class="text">Lorem ipsum.</div>
JQuery Code:
$(document).ready(function(){
var DivWidth = $(".text").width();
$(".left").click(function(){
$(".text").animate({
width: 0
});
});
$(".right").click(function(){
$(".text").animate({
width: DivWidth
});
});
});
You can see an example here: How to slide toggle a DIV from Left to Right?
This seems to take care of business pretty well. A fidde is here:
<label for="upload-file">A proper input label</label>
<div class="upload-button">
<div class="upload-cover">
Upload text or whatevers
</div>
<!-- this is later in the source so it'll be "on top" -->
<input name="upload-file" type="file" />
</div> <!-- .upload-button -->
/* first things first - get your box-model straight*/
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
label {
/* just positioning */
float: left;
margin-bottom: .5em;
}
.upload-button {
/* key */
position: relative;
overflow: hidden;
/* just positioning */
float: left;
clear: left;
}
.upload-cover {
/* basically just style this however you want - the overlaying file upload should spread out and fill whatever you turn this into */
background-color: gray;
text-align: center;
padding: .5em 1em;
border-radius: 2em;
border: 5px solid rgba(0,0,0,.1);
cursor: pointer;
}
.upload-button input[type="file"] {
display: block;
position: absolute;
top: 0; left: 0;
margin-left: -75px; /* gets that button with no-pointer-cursor off to the left and out of the way */
width: 200%; /* over compensates for the above - I would use calc or sass math if not here*/
height: 100%;
opacity: .2; /* left this here so you could see. Make it 0 */
cursor: pointer;
border: 1px solid red;
}
.upload-button:hover .upload-cover {
background-color: #f06;
}
The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.
{{ Request::segment(1) }}
The other answers that involve writing a custom Collector
are probably more efficient (such as Louis Wasserman's, +1), but if you want brevity, I'd suggest the following:
List<User> result = users.stream()
.filter(user -> user.getId() == 1)
.limit(2)
.collect(Collectors.toList());
Then verify the size of the result list.
if (result.size() != 1) {
throw new IllegalStateException("Expected exactly one user but got " + result);
User user = result.get(0);
}
Array.Sort(array, (a, b) => { return a[0] - b[0]; });
Try This:
$.ajax({
url:"",
type: "POST",
data: new FormData($('#uploadDatabaseForm')[0]),
contentType:false,
cache: false,
processData:false,
success:function (msg) {}
});
The latest JDBC MSSQL connectivity driver can be found on JDBC 4.0
The class file should be in the classpath. If you are using eclipse you can easily do the same by doing the following -->
Right Click Project Name --> Properties --> Java Build Path --> Libraries --> Add External Jars
Also as already been pointed out by @Cheeso the correct way to access is jdbc:sqlserver://server:port;DatabaseName=dbname
Meanwhile please find a sample class for accessing MSSQL DB (2008 in my case).
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from SampleTable";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://xx.xx.xx.xxxx:1433;databaseName=MyDBName", "DB_USER","DB_PASSWORD");
}
}
Hope this helps.
Concat date of one column with a time of another column in MySQL.
SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
Angular 4 empty data if else
if(this.data == 0)
{
alert("Null data");
}
else
{
//some logic
}
Or this:
f(x)=\begin{cases}
0, & -\pi\leqslant x <0\\
\pi, & 0 \leqslant x \leqslant +\pi
\end{cases}
If you are using it with Hibernate, you'll have to explicitly define the annotation CascadeType.DELETE_ORPHAN
, which can be used in conjunction with JPA CascadeType.ALL
.
If you don't plan to use Hibernate, you'll have to explicitly first delete the child elements and then delete the main record to avoid any orphan records.
execution sequence
With JPA 2.0, you can now use the option orphanRemoval = true
@OneToMany(mappedBy="foo", orphanRemoval=true)
I fixed the ERROR with three steps
1. I checked for the problem SOURCE
2. Provided the correct string/text, because it was the CAUSE
3. I cleaned the project, you ll see it under BUILD.
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
You can use the core with GDB in many ways, but passing parameters which is to be passed to the executable to GDB is not the way to use the core file. This could also be the reason you got that error. You can use the core file in the following ways:
gdb <executable> <core-file>
or gdb <executable> -c <core-file>
or
gdb <executable>
...
(gdb) core <core-file>
When using the core file you don't have to pass arguments. The crash scenario is shown in GDB (checked with GDB version 7.1 on Ubuntu).
For example:
$ ./crash -p param1 -o param2
Segmentation fault (core dumped)
$ gdb ./crash core
GNU gdb (GDB) 7.1-ubuntu
...
Core was generated by `./crash -p param1 -o param2'. <<<<< See this line shows crash scenario
Program terminated with signal 11, Segmentation fault.
#0 __strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99 ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)
If you want to pass parameters to the executable to be debugged in GDB, use --args
.
For example:
$ gdb --args ./crash -p param1 -o param2
GNU gdb (GDB) 7.1-ubuntu
...
(gdb) r
Starting program: /home/@@@@/crash -p param1 -o param2
Program received signal SIGSEGV, Segmentation fault.
__strlen_ia32 () at ../sysdeps/i386/i686/multiarch/../../i586/strlen.S:99
99 ../sysdeps/i386/i686/multiarch/../../i586/strlen.S: No such file or directory.
in ../sysdeps/i386/i686/multiarch/../../i586/strlen.S
(gdb)
Man pages will be helpful to see other GDB options.
When you want to have cross component interaction, then you need to know what are @Input , @Output , EventEmitter and Subjects.
If the relation between components is parent- child or vice versa we use @input & @output with event emitter..
@output emits an event and you need to emit using event emitter.
If it's not parent child relationship.. then you have to use subjects or through a common service.
This problem can be easily solved by installing the following Individual components:
FFMpeg can do this by seeking to the given timestamp and extracting exactly one frame as an image, see for instance:
ffmpeg -i input_file.mp4 -ss 01:23:45 -vframes 1 output.jpg
Let's explain the options:
-i input file the path to the input file
-ss 01:23:45 seek the position to the specified timestamp
-vframes 1 only handle one video frame
output.jpg output filename, should have a well-known extension
The -ss
parameter accepts a value in the form HH:MM:SS[.xxx]
or as a number in seconds. If you need a percentage, you need to compute the video duration beforehand.
nawk '$0 ~ /string$/ {printf "%s ",$0; getline; printf "%s\n", $0}' filename
This reads as
$0 ~ /string$/ ## matches any lines that end with the word string
printf ## so print the first line without newline
getline ## get the next line
printf "%s\n" ## print the whole line and carriage return
Although the top answers are correct, I personally like to work with attached properties to enable the solution to be applied to any UIElement
, especially when the Window
is not aware of the element that should be focused. In my experience I often see a composition of several view models and user controls, where the window is often nothing more that the root container.
public sealed class AttachedProperties
{
// Define the key gesture type converter
[System.ComponentModel.TypeConverter(typeof(System.Windows.Input.KeyGestureConverter))]
public static KeyGesture GetFocusShortcut(DependencyObject dependencyObject)
{
return (KeyGesture)dependencyObject?.GetValue(FocusShortcutProperty);
}
public static void SetFocusShortcut(DependencyObject dependencyObject, KeyGesture value)
{
dependencyObject?.SetValue(FocusShortcutProperty, value);
}
/// <summary>
/// Enables window-wide focus shortcut for an <see cref="UIElement"/>.
/// </summary>
// Using a DependencyProperty as the backing store for FocusShortcut. This enables animation, styling, binding, etc...
public static readonly DependencyProperty FocusShortcutProperty =
DependencyProperty.RegisterAttached("FocusShortcut", typeof(KeyGesture), typeof(AttachedProperties), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, new PropertyChangedCallback(OnFocusShortcutChanged)));
private static void OnFocusShortcutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is UIElement element) || e.NewValue == e.OldValue)
return;
var window = FindParentWindow(d);
if (window == null)
return;
var gesture = GetFocusShortcut(d);
if (gesture == null)
{
// Remove previous added input binding.
for (int i = 0; i < window.InputBindings.Count; i++)
{
if (window.InputBindings[i].Gesture == e.OldValue && window.InputBindings[i].Command is FocusElementCommand)
window.InputBindings.RemoveAt(i--);
}
}
else
{
// Add new input binding with the dedicated FocusElementCommand.
// see: https://gist.github.com/shuebner20/349d044ed5236a7f2568cb17f3ed713d
var command = new FocusElementCommand(element);
window.InputBindings.Add(new InputBinding(command, gesture));
}
}
}
With this attached property you can define a focus shortcut for any UIElement. It will automatically register the input binding at the window containing the element.
<TextBox x:Name="SearchTextBox"
Text={Binding Path=SearchText}
local:AttachedProperties.FocusShortcutKey="Ctrl+Q"/>
The full sample including the FocusElementCommand implementation is available as gist: https://gist.github.com/shuebner20/c6a5191be23da549d5004ee56bcc352d
Disclaimer: You may use this code everywhere and free of charge. Please keep in mind, that this is a sample that is not suitable for heavy usage. For example, there is no garbage collection of removed elements because the Command will hold a strong reference to the element.
This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.
It is called like,
IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);
where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.
DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;
An interface class looks like,
class IMyInterface
{
DEFINE_INTERFACE(IMyInterface);
public:
virtual ~IMyInterface() {};
virtual void MyMethod1() = 0;
...
};
The header file is like this
#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED
#pragma once
The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.
#define SN_APPLY_LIBRARIES(L, A) \
L(A, sn, "sn.dll") \
L(A, http_server_lib, "http_server_lib.dll") \
L(A, http_server, "")
Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.
#define SN_APPLY_ENTRYPOINTS_sn(M) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def) \
M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)
#define SN_APPLY_ENTRYPOINTS_http_server_lib(M) \
M(IHTTP_Server, HTTP::server::server, http_server_lib, def)
#define SN_APPLY_ENTRYPOINTS_http_server(M)
With the libraries all setup, the header file uses the macro definitions to define the needful.
#define APPLY_ENTRY(A, N, L) \
SN_APPLY_ENTRYPOINTS_##N(A)
#define DEFINE_INTERFACE(I) \
public: \
static const long Id = SN::I##_def_entry; \
private:
namespace SN
{
#define DEFINE_LIBRARY_ENUM(A, N, L) \
N##_library,
This creates an enum for the libraries.
enum LibraryValues
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
LastLibrary
};
#define DEFINE_ENTRY_ENUM(I, C, L, D) \
I##_##D##_entry,
This creates an enum for interface implementations.
enum EntryValues
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
LastEntry
};
long CallEntryPoint(long id, long interfaceId);
This defines the factory class. Not much to it here.
template <class I>
class SN_Factory
{
public:
SN_Factory()
{
}
static I *CreateObject(long id = I::Id )
{
return (I *)CallEntryPoint(id, I::Id);
}
};
}
#endif //SN_FACTORY_H_INCLUDED
Then the CPP is,
#include "sn_factory.h"
#include <windows.h>
Create the external entry point. You can check that it exists using depends.exe.
extern "C"
{
__declspec(dllexport) long entrypoint(long id)
{
#define CREATE_OBJECT(I, C, L, D) \
case SN::I##_##D##_entry: return (int) new C();
switch (id)
{
SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
case -1:
default:
return 0;
}
}
}
The macros set up all the data needed.
namespace SN
{
bool loaded = false;
char * libraryPathArray[SN::LastLibrary];
#define DEFINE_LIBRARY_PATH(A, N, L) \
libraryPathArray[N##_library] = L;
static void LoadLibraryPaths()
{
SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
}
typedef long(*f_entrypoint)(long id);
f_entrypoint libraryFunctionArray[LastLibrary - 1];
void InitlibraryFunctionArray()
{
for (long j = 0; j < LastLibrary; j++)
{
libraryFunctionArray[j] = 0;
}
#define DEFAULT_LIBRARY_ENTRY(A, N, L) \
libraryFunctionArray[N##_library] = &entrypoint;
SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
}
enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
#define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
libraryForEntryPointArray[I##_##D##_entry] = L##_library;
void LoadLibraryForEntryPointArray()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
}
enum SN::EntryValues defaultEntryArray[SN::LastEntry];
#define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
defaultEntryArray[I##_##D##_entry] = I##_def_entry;
void LoadDefaultEntries()
{
SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
}
void Initialize()
{
if (!loaded)
{
loaded = true;
LoadLibraryPaths();
InitlibraryFunctionArray();
LoadLibraryForEntryPointArray();
LoadDefaultEntries();
}
}
long CallEntryPoint(long id, long interfaceId)
{
Initialize();
// assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
enum SN::LibraryValues l = libraryForEntryPointArray[id];
f_entrypoint f = libraryFunctionArray[l];
if (!f)
{
HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);
if (!hGetProcIDDLL) {
return NULL;
}
// resolve function address here
f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
if (!f) {
return NULL;
}
libraryFunctionArray[l] = f;
}
return f(id);
}
}
Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.
#include "sn_pch.h"
Setup this library.
#define SN_APPLY_CURRENT_LIBRARY(L, A) \
L(A, sn, "sn.dll")
An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.
#include "../inc/sn_factory.cpp"
vehicle[] car = new vehicle[N];
In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:
var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');
Use something like this (Not compiler checked)
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSRange range=[self.myLabel.text rangeOfString:texts[sliderValue]]; //myLabel is the outlet from where you will get the text, it can be same or different
NSArray *colors=@[[UIColor redColor],
[UIColor redColor],
[UIColor yellowColor],
[UIColor greenColor]
];
[string addAttribute:NSForegroundColorAttributeName
value:colors[sliderValue]
range:range];
[self.scanLabel setAttributedText:texts[sliderValue]];
A little late, but I use a _is_running
variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.
def stop(self):
self._is_running = False
And in run()
just loop on while(self._is_running)
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
This prints the key combination directly to the image:
The first window shows 'z'
pressed, the second shows 'ctrl' + 'z'
pressed. When a key combination is used, a question mark appear.
Don't mess up with the question mark code, which is 63
.
import numpy as np
import cv2
im = np.zeros((100, 300), np.uint8)
cv2.imshow('Keypressed', im)
while True:
key = cv2.waitKey(0)
im_c = im.copy()
cv2.putText(
im_c,
f'{chr(key)} -> {key}',
(10, 60),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(255,255,255),
2)
cv2.imshow('Keypressed', im_c)
if key == 27: break # 'ESC'
Object.values()
is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.
Solution: use es2017
or es2017.object
in your --lib
compiler option.
For example, using tsconfig.json
:
"compilerOptions": {
"lib": ["es2017", "dom"]
}
Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values
), it's up to you to polyfill your project code yourself if you want. And since Object.values
is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js
will do the job.
<script>
//$(document).ready(function () {
function showcontent() {
document.getElementById("demo22").innerHTML = "Hello World";
}
//});// end of ready function
</script>
I had the same problem where onclick function calls would not work. I had included the function inside the usual "$(document).ready(function(){});" block used to wrap jquery scripts. Commenting this block out solved the problem.
After JAVAEE8 published , now you can use the new JAVAEE API JSON-B (JSR367)
Maven dependency :
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.eclipse</groupId>
<artifactId>yasson</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
Here is some code snapshot :
Jsonb jsonb = JsonbBuilder.create();
// Two important API : toJson fromJson
String result = jsonb.toJson(listaDePontos);
JSON-P is also updated to 1.1 and more easy to use. JSON-P 1.1 (JSR374)
Maven dependency :
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1</version>
</dependency>
Here is the runnable code snapshot :
String data = "{\"name\":\"Json\","
+ "\"age\": 29,"
+ " \"phoneNumber\": [10000,12000],"
+ "\"address\": \"test\"}";
JsonObject original = Json.createReader(new StringReader(data)).readObject();
/**getValue*/
JsonPointer pAge = Json.createPointer("/age");
JsonValue v = pAge.getValue(original);
System.out.println("age is " + v.toString());
JsonPointer pPhone = Json.createPointer("/phoneNumber/1");
System.out.println("phoneNumber 2 is " + pPhone.getValue(original).toString());
Use a CultureInfo like this, from MSDN:
// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");
// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));
More info on MSDN. Here is a link of all different cultures.