Big screen:
Small screen (Mobile)
if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview
CSS + HTML + JQUERY :
_x000D_
@import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
body {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
background: #fafafa;_x000D_
}_x000D_
_x000D_
p {_x000D_
font-family: 'Poppins', sans-serif;_x000D_
font-size: 1.1em;_x000D_
font-weight: 300;_x000D_
line-height: 1.7em;_x000D_
color: #999;_x000D_
}_x000D_
_x000D_
a,_x000D_
a:hover,_x000D_
a:focus {_x000D_
color: inherit;_x000D_
text-decoration: none;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
.navbar {_x000D_
padding: 15px 10px;_x000D_
background: #fff;_x000D_
border: none;_x000D_
border-radius: 0;_x000D_
margin-bottom: 40px;_x000D_
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
}_x000D_
_x000D_
.navbar-btn {_x000D_
box-shadow: none;_x000D_
outline: none !important;_x000D_
border: none;_x000D_
}_x000D_
_x000D_
.line {_x000D_
width: 100%;_x000D_
height: 1px;_x000D_
border-bottom: 1px dashed #ddd;_x000D_
margin: 40px 0;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#sidebar {_x000D_
width: 250px;_x000D_
position: fixed;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100vh;_x000D_
z-index: 999;_x000D_
background: #7386D5;_x000D_
color: #fff !important;_x000D_
transition: all 0.3s;_x000D_
}_x000D_
_x000D_
#sidebar.active {_x000D_
margin-left: -250px;_x000D_
}_x000D_
_x000D_
#sidebar .sidebar-header {_x000D_
padding: 20px;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
#sidebar ul.components {_x000D_
padding: 20px 0;_x000D_
border-bottom: 1px solid #47748b;_x000D_
}_x000D_
_x000D_
#sidebar ul p {_x000D_
color: #fff;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
#sidebar ul li a {_x000D_
padding: 10px;_x000D_
font-size: 1.1em;_x000D_
display: block;_x000D_
color:white;_x000D_
}_x000D_
_x000D_
#sidebar ul li a:hover {_x000D_
color: #7386D5;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
#sidebar ul li.active>a,_x000D_
a[aria-expanded="true"] {_x000D_
color: #fff;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
a[data-toggle="collapse"] {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
a[aria-expanded="false"]::before,_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e259';_x000D_
display: block;_x000D_
position: absolute;_x000D_
right: 20px;_x000D_
font-family: 'Glyphicons Halflings';_x000D_
font-size: 0.6em;_x000D_
}_x000D_
_x000D_
a[aria-expanded="true"]::before {_x000D_
content: '\e260';_x000D_
}_x000D_
_x000D_
ul ul a {_x000D_
font-size: 0.9em !important;_x000D_
padding-left: 30px !important;_x000D_
background: #6d7fcc;_x000D_
}_x000D_
_x000D_
ul.CTAs {_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
ul.CTAs a {_x000D_
text-align: center;_x000D_
font-size: 0.9em !important;_x000D_
display: block;_x000D_
border-radius: 5px;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
_x000D_
a.download {_x000D_
background: #fff;_x000D_
color: #7386D5;_x000D_
}_x000D_
_x000D_
a.article,_x000D_
a.article:hover {_x000D_
background: #6d7fcc !important;_x000D_
color: #fff !important;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
_x000D_
#content {_x000D_
width: calc(100% - 250px);_x000D_
padding: 40px;_x000D_
min-height: 100vh;_x000D_
transition: all 0.3s;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
#content.active {_x000D_
width: 100%;_x000D_
}_x000D_
/* ---------------------------------------------------_x000D_
MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
_x000D_
@media (max-width: 768px) {_x000D_
#sidebar {_x000D_
margin-left: -250px;_x000D_
}_x000D_
#sidebar.active {_x000D_
margin-left: 0;_x000D_
}_x000D_
#content {_x000D_
width: 100%;_x000D_
}_x000D_
#content.active {_x000D_
width: calc(100% - 250px);_x000D_
}_x000D_
#sidebarCollapse span {_x000D_
display: none;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
<title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
<!-- Bootstrap CSS CDN -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<!-- Our Custom CSS -->_x000D_
<link rel="stylesheet" href="style2.css">_x000D_
<!-- Scrollbar Custom CSS -->_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
<div class="wrapper">_x000D_
<!-- Sidebar Holder -->_x000D_
<nav id="sidebar">_x000D_
<div class="sidebar-header">_x000D_
<h3>Header as you want </h3>_x000D_
</h3>_x000D_
</div>_x000D_
_x000D_
<ul class="list-unstyled components">_x000D_
<p>Dummy Heading</p>_x000D_
<li class="active">_x000D_
<a href="#menu">Animación</a>_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
</li>_x000D_
<li>_x000D_
<a href="#menu">Interacción</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Blog</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">Acerca</a>_x000D_
</li>_x000D_
<li>_x000D_
<a href="#">contacto</a>_x000D_
</li>_x000D_
_x000D_
_x000D_
</ul>_x000D_
_x000D_
_x000D_
</nav>_x000D_
_x000D_
<!-- Page Content Holder -->_x000D_
<div id="content">_x000D_
_x000D_
<nav class="navbar navbar-default">_x000D_
<div class="container-fluid">_x000D_
_x000D_
<div class="navbar-header">_x000D_
<button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
<i class="glyphicon glyphicon-align-left"></i>_x000D_
<span>Toggle Sidebar</span>_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li><a href="#">Page</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
<!-- jQuery CDN -->_x000D_
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
<!-- Bootstrap Js CDN -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<!-- jQuery Custom Scroller CDN -->_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
_x000D_
_x000D_
$('#sidebarCollapse').on('click', function() {_x000D_
$('#sidebar, #content').toggleClass('active');_x000D_
$('.collapse.in').toggleClass('in');_x000D_
$('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
if this is what you want .
I have found that using jQuery the best solution is
$(this.form).submit()
Using this statement jquery plugins (e.g. jquery form plugin) works correctly and jquery DOM traversing overhead is minimized.
Jupyter is base on ipython, a permanent solution could be changing the ipython config options.
Create a config file
$ ipython profile create
$ ipython locate
/Users/username/.ipython
Edit the config file
$ cd /Users/username/.ipython
$ vi profile_default/ipython_config.py
The following lines allow you to add your module path to sys.path
c.InteractiveShellApp.exec_lines = [
'import sys; sys.path.append("/path/to/your/module")'
]
At the jupyter startup the previous line will be executed
Here you can find more details about ipython config https://www.lucypark.kr/blog/2013/02/10/when-python-imports-and-ipython-does-not/
Make sure you have installed HAXM installer
on your SDK Manager.
After you download it and make sure you run the setup located in: {SDK_FOLDER}\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm.exe
Note: in Android Studio, the command "intelhaxm.exe" has been changed to "intelhaxm-android.exe"
If you get the error "VT not supported" during the installation disable Hyper-V on windows features. You can execute this command dism.exe /Online /Disable-Feature:Microsoft-Hyper-V
. You will also need "Virtualization Technology" to be enabled on your BIOS
With the deprecation of GCM and removal of its APIs, it appears that you could see MismatchSenderId if you try to use GCM after May 29, 2019. See the Google GCM and FCM FAQ for more details.
WinDbg's Logger.exe is the closest to strace: https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/logger-and-logviewer
EDIT: There's also windbg's wt: https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/wt--trace-and-watch-data-
If I'm not mislead, you just need to set your local branches to track their pairs in the origin server.
Using your command line, you can try
git checkout mybranch
git branch --set-upstream-to=origin/mybranch
That will configure something as an equivalent of your local branch in the server. I'll bet that Android Studio is complaining about the lack of that.
If someone knows how to do this using the GUI of that IDE, that would be interesting to read. :)
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
There are multiple schemas for "JUnit" and "xUnit" results.
model/xsd
)Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd
which adds support for Erlang/OTP Junit format).
Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.
Seems that no one mentioned Query Express (http://www.albahari.com/queryexpress.aspx) and a fork Query ExPlus (also link at the bottom of http://www.albahari.com/queryexpress.aspx)
BTW. First URL is the home page of Joseph Albahari who is the author of LINQPad (check out this killer tool)
The accepted answer is good. But if you have a scenario like this:
http://www.mydomain.me/index.php?state=California.php#Berkeley
You can treat the named anchor as a query string like this:
http://www.mydomain.me/index.php?state=California.php&city=Berkeley
Then, access it like this:
$Url = $_GET['state']."#".$_GET['city'];
@@IDENTITY
Is a system function that returns the last-inserted identity value.
If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function
textscan()
Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.
$('#drop').change(
function() {
var val1 = $('#pick option:selected').val();
var val2 = $('#drop option:selected').val();
// Do something with val1 and val2 ...
}
);
<a download="custom-filename.jpg" href="/path/to/image" title="ImageName">
<img alt="ImageName" src="/path/to/image">
</a>
It's not yet fully supported caniuse, but you can use with modernizr (under Non-core detects) to check the support of the browser.
You have two options:
Option 1 (only works for bold, italic and underline):
String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(Html.fromHtml(s));
Option 2:
Use a Spannable; it is more complicated, but you can dynamically modify the text attributes (not only bold/italic, also colors).
If you want to use Netbeans to define tables read this https://codezone4.wordpress.com/2012/06/19/java-database-application-using-javadb-part-1/ Simply define column as integer and create database, then grab structure to a temporary file, then delete table. Right clik to tables folder and select recreate table, select saved file and edit script for auto increment.
Without examples of the dataset of staging this is a shot in the dark, but have you tried something like this?
update PRODUCTION p,
staging s
set p.name = s.name
p.count = s.count
where p.id = s.id
This would work assuming the id column matches on both tables.
To get every part of the URL except for the query:
var url = (location.origin).concat(location.pathname).concat(location.hash);
Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash)
.
It's better practice to use concat
to join Javascript strings together (rather than +
): in some situations it avoids problems such as type confusion.
To fix up the second method in Jeff Hillman's post, you could either do a:
$app = Get-WmiObject
-Query "SELECT * FROM Win32_Product WHERE Name = 'Software Name'"
Or
$app = Get-WmiObject -Class Win32_Product `
-Filter "Name = 'Software Name'"
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
You can try this nice little trick for C++. Take the expression which gives you the array and then append a comma and the number of elements you want to see. Expanding that value will show you elements 0-(N-1) where N is the number you add after the comma.
For example if pArray
is the array, type pArray,10
in the watch window.
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
Where it is documented:
From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"
collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!
The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,
Class Dog
has_many :tags
belongs_to :person
end
Class Person
has_many :dogs
end
d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")
or even
t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")
You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)
How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)
Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color
is the fastest to respond (subjective).
Add the following to your body and your links will have a tap effect.
body {
-webkit-tap-highlight-color: #ccc;
}
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(pdfIntent );
}
catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,
"No Application available to viewPDF",
Toast.LENGTH_SHORT).show();
}
}
How do I display and redirect output to a file. Suppose if I use dos command, dir > test.txt ,this command will redirect output to file test.txt without displaying the results. how to write a command to display the output and redirect output to a file using DOS i.e., windows command prompt, not in UNIX/LINUX.
You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.
var str output
lf > $output
echo $output # Will show output on screen.
echo $output > "test.txt" # Will write output to file test.txt.
system start "test.txt" # Will open file test.txt for viewing/editing.
To substantiate @deceze's claim that the default JSON encoding is UTF-8...
From IETF RFC4627:
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets.
00 00 00 xx UTF-32BE 00 xx 00 xx UTF-16BE xx 00 00 00 UTF-32LE xx 00 xx 00 UTF-16LE xx xx xx xx UTF-8
I also faced similar problem.If you have already reserved url then you have to first delete the url to run in non admin mode else it will fail with Access is Denied error.
netsh http delete urlacl url=http://+:80
There are a few reasons:
I find it aids maintenence to separate markup, i.e. the HTML and client-side scripts. For example, jQuery makes it easy to add event handlers programatically.
The example you give would be broken in any user agent that doesn't support javascript, or has javascript turned off. The concept of progressive enhancement would encourage a simple hyperlink to /map/
for user agents without javascript, then adding a click handler prgramatically for user agents that support javascript.
For example:
Markup:
<a id="example" href="/map/">link</a>
Javascript:
$(document).ready(function(){
$("#example").click(function(){
popup('/map/', 300, 300, 'map');
return false;
});
})
It may be possible to use C to write programs that behave robustly in such environments, but only if most forms of compiler optimization are disabled. Optimizing compilers are designed to replace many seemingly-redundant coding patterns with "more efficient" ones, and may have no clue that the reason the programmer is testing x==42
when the compiler knows there's no way x
could possibly hold anything else is because the programmer wants to prevent the execution of certain code with x
holding some other value--even in cases where the only way it could hold that value would be if the system received some kind of electrical glitch.
Declaring variables as volatile
is often helpful, but may not be a panacea.
Of particular importance, note that safe coding often requires that dangerous
operations have hardware interlocks that require multiple steps to activate,
and that code be written using the pattern:
... code that checks system state
if (system_state_favors_activation)
{
prepare_for_activation();
... code that checks system state again
if (system_state_is_valid)
{
if (system_state_favors_activation)
trigger_activation();
}
else
perform_safety_shutdown_and_restart();
}
cancel_preparations();
If a compiler translates the code in relatively literal fashion, and if all
the checks for system state are repeated after the prepare_for_activation()
,
the system may be robust against almost any plausible single glitch event,
even those which would arbitrarily corrupt the program counter and stack. If
a glitch occurs just after a call to prepare_for_activation()
, that would imply
that activation would have been appropriate (since there's no other reason
prepare_for_activation()
would have been called before the glitch). If the
glitch causes code to reach prepare_for_activation()
inappropriately, but there
are no subsequent glitch events, there would be no way for code to subsequently
reach trigger_activation()
without having passed through the validation check or calling cancel_preparations first [if the stack glitches, execution might proceed to a spot just before trigger_activation()
after the context that called prepare_for_activation()
returns, but the call to cancel_preparations()
would have occurred between the calls to prepare_for_activation()
and trigger_activation()
, thus rendering the latter call harmless.
Such code may be safe in traditional C, but not with modern C compilers. Such compilers can be very dangerous in that sort of environment because aggressive they strive to only include code which will be relevant in situations that could come about via some well-defined mechanism and whose resulting consequences would also be well defined. Code whose purpose would be to detect and clean up after failures may, in some cases, end up making things worse. If the compiler determines that the attempted recovery would in some cases invoke undefined behavior, it may infer that the conditions that would necessitate such recovery in such cases cannot possibly occur, thus eliminating the code that would have checked for them.
Here's a start.. Open to suggestions/improvements.
Server
public class ChatHub : Hub
{
public void SendChatMessage(string who, string message)
{
string name = Context.User.Identity.Name;
Clients.Group(name).addChatMessage(name, message);
Clients.Group("[email protected]").addChatMessage(name, message);
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
Groups.Add(Context.ConnectionId, name);
return base.OnConnected();
}
}
JavaScript
(Notice how addChatMessage
and sendChatMessage
are also methods in the server code above)
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.addChatMessage = function (who, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(who).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#chat').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
Testing
If you would like to use a formula, the TRIM
function will do exactly what you're looking for:
+----+------------+---------------------+
| | A | B |
+----+------------+---------------------+
| 1 | =TRIM(B1) | value to trim here |
+----+------------+---------------------+
So to do the whole column...
1) Insert a column
2) Insert TRIM
function pointed at cell you are trying to correct.
3) Copy formula down the page
4) Copy inserted column
5) Paste as "Values"
Should be good to go from there...
You can do this without any JavaScript involved
(Using accepted answer)
HTML
<table class="table table-bordered table-striped">
<tr>
<td><button class="btn" data-target="#collapseme" data-toggle="collapse" type="button">Click to expand</button></td>
</tr>
<tr>
<td class="nopadding">
<div class="collapse" id="collapseme">
<div class="content">
Show me collapsed
</div>
</div>
</td>
</tr>
</table>
CSS
.nopadding {
padding: 0 !important;
}
.content {
padding: 20px;
}
Another way to do this is by using the bitstring
module:
>>> from bitstring import BitArray
>>> b = BitArray(bin='11111111')
>>> b.uint
255
Note that the unsigned integer is different from the signed integer:
>>> b.int
-1
The bitstring
module isn't a requirement, but it has lots of performant methods for turning input into and from bits into other forms, as well as manipulating them.
With the helpful advice from people who have answered here I started digging into One-Jar. After some dead-ends (and some results that were exactly like my previous results I managed to get it working. For other peoples reference I'm listing the build.xml that worked for me.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="build" name="<INSERT_PROJECT_NAME_HERE>">
<property environment="env"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="one-jar.dist.dir" value="../onejar"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>
<property name="build.dir" value="build"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.target.dir" value="${build.dir}/jars"/>
<property name="external.lib.dir" value="../jars"/>
<property name="final.jar" value="${bin.dir}/<INSERT_NAME_OF_FINAL_JAR_HERE>"/>
<property name="main.class" value="<INSERT_MAIN_CLASS_HERE>"/>
<path id="project.classpath">
<fileset dir="${external.lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<target name="init">
<mkdir dir="${bin.dir}"/>
<mkdir dir="${build.dir}"/>
<mkdir dir="${classes.dir}"/>
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="${build.dir}"/>
<delete dir="${bin.dir}"/>
</target>
<target name="cleanall" depends="clean"/>
<target name="build" depends="init">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
<src path="${src.dir}"/>
<classpath refid="project.classpath"/>
</javac>
</target>
<target name="build-jar" depends="build">
<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
<main>
<fileset dir="${classes.dir}"/>
</main>
<lib>
<fileset dir="${external.lib.dir}" />
</lib>
</one-jar>
</target>
</project>
I hope someone else can benefit from this.
PHP has a built in function called json_decode(). Just pass the JSON string into this function and it will convert it to the PHP equivalent string, array or object.
In order to pass it as a string from Javascript, you can convert it to JSON using
JSON.stringify(object);
or a library such as Prototype
I have another solution: that solution works perfectly when you have only content you want to show when you are logged in. Define a rule where you checking if you are logged in and its not path of whitelist routes.
$urlRouterProvider.rule(function ($injector, $location) {
var UserService = $injector.get('UserService');
var path = $location.path(), normalized = path.toLowerCase();
if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
$location.path('/login/signin');
}
});
In my example i ask if i am not logged in and the current route i want to route is not part of `/login', because my whitelist routes are the following
/login/signup // registering new user
/login/signin // login to app
so i have instant access to this two routes and every other route will be checked if you are online.
Here is my whole routing file for the login module
export default (
$stateProvider,
$locationProvider,
$urlRouterProvider
) => {
$stateProvider.state('login', {
parent: 'app',
url: '/login',
abstract: true,
template: '<ui-view></ui-view>'
})
$stateProvider.state('signin', {
parent: 'login',
url: '/signin',
template: '<login-signin-directive></login-signin-directive>'
});
$stateProvider.state('lock', {
parent: 'login',
url: '/lock',
template: '<login-lock-directive></login-lock-directive>'
});
$stateProvider.state('signup', {
parent: 'login',
url: '/signup',
template: '<login-signup-directive></login-signup-directive>'
});
$urlRouterProvider.rule(function ($injector, $location) {
var UserService = $injector.get('UserService');
var path = $location.path();
if (!UserService.isLoggedIn() && path.indexOf('login') === -1) {
$location.path('/login/signin');
}
});
$urlRouterProvider.otherwise('/error/not-found');
}
() => { /* code */ }
is ES6 syntax, use instead function() { /* code */ }
To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.
Here's what I did:
var timestamp = moment.unix({{ time }});
var utcOffset = moment().utcOffset();
var local_time = timestamp.add(utcOffset, "minutes");
var dateString = local_time.fromNow();
Where {{ time }}
is the utc timestamp.
$('[name="CheckboxName"]:checked').each(function () {
// do stuff
});
If you have access to an Intel Secure Key compatible CPU, you can generate real random numbers and strings using these libraries: https://github.com/JebteK/RdRand and https://www.rdrand.com/
Just download the latest version from here, include Jebtek.RdRand and add a using statement for it. Then, all you need to do is this:
bool isAvailable = RdRandom.GeneratorAvailable(); //Check to see if this is a compatible CPU
string key = RdRandom.GenerateKey(10); //Generate 10 random characters
Plus, you also get these additional capabilities:
string apiKey = RdRandom.GenerateAPIKey(); //Generate 64 random characters, useful for API keys
byte[] b = RdRandom.GenerateBytes(10); //Generate an array of 10 random bytes
uint i = RdRandom.GenerateUnsignedInt() //Generate a random unsigned int
If you don't have a compatible CPU to execute the code on, just use the RESTful services at rdrand.com. With the RdRandom wrapper library included in your project, you would just need to do this (you get 1000 free calls when you signup):
string ret = Randomizer.GenerateKey(<length>, "<key>");
You can also generate random byte arrays and unsigned integers as follows:
uint ret = Randomizer.GenerateUInt("<key>");
byte[] ret = Randomizer.GenerateBytes(<length>, "<key>");
For those users of wamp server, follow the first 2 steps of @Raul Chipad's solution then:
I compile Kotlin to byte code and then de-compile that to Java. I compile with the Kotlin compiler and de-compile with cfr.
My project is here.
This allows me to compile this:
package functionsiiiandiiilambdas.functions.p01tailiiirecursive
tailrec fun findFixPoint(x: Double = 1.0): Double =
if (x == Math.cos(x)) x else findFixPoint(Math.cos(x))
To this:
package functionsiiiandiiilambdas.functions.p01tailiiirecursive;
public final class ExampleKt {
public static final double findFixPoint(double x) {
while (x != Math.cos(x)) {
x = Math.cos(x);
}
return x;
}
public static /* bridge */ /* synthetic */ double findFixPoint$default(
double d, int n, Object object) {
if ((n & 1) != 0) {
d = 1.0;
}
return ExampleKt.findFixPoint(d);
}
}
None of the answers here satisfies my needs.
The answer from Muno is wrong because it lists ONLY the USB ports.
The answer from code4life is wrong because it lists all EXCEPT the USB ports. (Nevertheless it has 44 up-votes!!!)
I have an EPSON printer simulation port on my computer which is not listed by any of the answers here. So I had to write my own solution. Additionally I want to display more information than just the caption string. I also need to separate the port name from the description.
My code has been tested on Windows XP, Windows 7 and Windows 10.
The Port Name (like "COM1") must be read from the registry because WMI does not give this information for all COM ports (EPSON).
If you use my code you do not need SerialPort.GetPortNames()
anymore. My function returns the same ports, but with additional details. Why did Microsoft not implement such a function into the framework??
using System.Management;
using Microsoft.Win32;
using (ManagementClass i_Entity = new ManagementClass("Win32_PnPEntity"))
{
foreach (ManagementObject i_Inst in i_Entity.GetInstances())
{
Object o_Guid = i_Inst.GetPropertyValue("ClassGuid");
if (o_Guid == null || o_Guid.ToString().ToUpper() != "{4D36E978-E325-11CE-BFC1-08002BE10318}")
continue; // Skip all devices except device class "PORTS"
String s_Caption = i_Inst.GetPropertyValue("Caption") .ToString();
String s_Manufact = i_Inst.GetPropertyValue("Manufacturer").ToString();
String s_DeviceID = i_Inst.GetPropertyValue("PnpDeviceID") .ToString();
String s_RegPath = "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\" + s_DeviceID + "\\Device Parameters";
String s_PortName = Registry.GetValue(s_RegPath, "PortName", "").ToString();
int s32_Pos = s_Caption.IndexOf(" (COM");
if (s32_Pos > 0) // remove COM port from description
s_Caption = s_Caption.Substring(0, s32_Pos);
Console.WriteLine("Port Name: " + s_PortName);
Console.WriteLine("Description: " + s_Caption);
Console.WriteLine("Manufacturer: " + s_Manufact);
Console.WriteLine("Device ID: " + s_DeviceID);
Console.WriteLine("-----------------------------------");
}
}
I tested the code with a lot of COM ports. This is the Console output:
Port Name: COM29
Description: CDC Interface (Virtual COM Port) for USB Debug
Manufacturer: GHI Electronics, LLC
Device ID: USB\VID_1B9F&PID_F003&MI_01\6&3009671A&0&0001
-----------------------------------
Port Name: COM28
Description: Teensy USB Serial
Manufacturer: PJRC.COM, LLC.
Device ID: USB\VID_16C0&PID_0483\1256310
-----------------------------------
Port Name: COM25
Description: USB-SERIAL CH340
Manufacturer: wch.cn
Device ID: USB\VID_1A86&PID_7523\5&2499667D&0&3
-----------------------------------
Port Name: COM26
Description: Prolific USB-to-Serial Comm Port
Manufacturer: Prolific
Device ID: USB\VID_067B&PID_2303\5&2499667D&0&4
-----------------------------------
Port Name: COM1
Description: Comunications Port
Manufacturer: (Standard port types)
Device ID: ACPI\PNP0501\1
-----------------------------------
Port Name: COM999
Description: EPSON TM Virtual Port Driver
Manufacturer: EPSON
Device ID: ROOT\PORTS\0000
-----------------------------------
Port Name: COM20
Description: EPSON COM Emulation USB Port
Manufacturer: EPSON
Device ID: ROOT\PORTS\0001
-----------------------------------
Port Name: COM8
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&000F\8&3ADBDF90&0&001DA568988B_C00000000
-----------------------------------
Port Name: COM9
Description: Standard Serial over Bluetooth link
Manufacturer: Microsoft
Device ID: BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000\8&3ADBDF90&0&000000000000_00000002
-----------------------------------
Port Name: COM30
Description: Arduino Uno
Manufacturer: Arduino LLC (www.arduino.cc)
Device ID: USB\VID_2341&PID_0001\74132343530351F03132
-----------------------------------
COM1 is a COM port on the mainboard.
COM 8 and 9 are Buetooth COM ports.
COM 25 and 26 are USB to RS232 adapters.
COM 28 and 29 and 30 are Arduino-like boards.
COM 20 and 999 are EPSON ports.
This will print all the subdirectories of the current directory:
print [name for name in os.listdir(".") if os.path.isdir(name)]
I'm not sure what you're doing with split("-")
, but perhaps this code will help you find a solution?
If you want the full pathnames of the directories, use abspath
:
print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk
as others have suggested.
There's very little reason not to open multiple workbooks in Excel. Key lines of code are:
Application.EnableEvents = False
Application.ScreenUpdating = False
...then you won't see anything whilst the code runs, and no code will run that is associated with the opening of the second workbook. Then there are...
Application.DisplayAlerts = False
Application.Calculation = xlManual
...so as to stop you getting pop-up messages associated with the content of the second file, and to avoid any slow re-calculations. Ensure you set back to True/xlAutomatic at end of your programming
If opening the second workbook is not going to cause performance issues, you may as well do it. In fact, having the second workbook open will make it very beneficial when attempting to debug your code if some of the secondary files do not conform to the expected format
Here is some expert guidance on using multiple Excel files that gives an overview of the different methods available for referencing data
An extension question would be how to cycle through multiple files contained in the same folder. You can use the Windows folder picker using:
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .Selected.Items.Count = 1 the InputFolder = .SelectedItems(1)
End With
FName = VBA.Dir(InputFolder)
Do While FName <> ""
'''Do function here
FName = VBA.Dir()
Loop
Hopefully some of the above will be of use
It is also possible to use Object.freeze
on you class(es6)/constructor function(es5) object to make it immutable:
class MyConstants {}
MyConstants.staticValue = 3;
MyConstants.staticMethod = function() {
return 4;
}
Object.freeze(MyConstants);
// after the freeze, any attempts of altering the MyConstants class will have no result
// (either trying to alter, add or delete a property)
MyConstants.staticValue === 3; // true
MyConstants.staticValue = 55; // will have no effect
MyConstants.staticValue === 3; // true
MyConstants.otherStaticValue = "other" // will have no effect
MyConstants.otherStaticValue === undefined // true
delete MyConstants.staticMethod // false
typeof(MyConstants.staticMethod) === "function" // true
Trying to alter the class will give you a soft-fail (won't throw any errors, it will simply have no effect).
Thanks to Renato answer, I have created a really basic example:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
It will just print your global git username :)
This is how I login to my servers.
ssp <server_ip>
#!/bin/bash
sshpass -p mypassword ssh root@$1
And therefore...
ssp server_ip
use jquery
$("#item").change(function({
var x=$(this).val();
});
Your value will be in x
variable, use this variable value in your jsp, like this {x}
this statement will give the value
I don't have a machine available to test this but it should work. First you will probably need to install the either the 2007 Office System Driver: Data Connectivity Components or the Microsoft Access Database Engine 2010 Redistributable. Then try the following code, note you will need to change the name of the Sheet in the Select statement below to match sheetname in your excel file:
using System.Data;
using System.Data.OleDb;
namespace Data_Migration_Process_Creator
{
class Class1
{
private DataTable GetDataTable(string sql, string connectionString)
{
DataTable dt = null;
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader rdr = cmd.ExecuteReader())
{
dt.Load(rdr);
return dt;
}
}
}
}
private void GetExcel()
{
string fullPathToExcel = "<Path to Excel file>"; //ie C:\Temp\YourExcel.xls
string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes'", fullPathToExcel);
DataTable dt = GetDataTable("SELECT * from [SheetName$]", connString);
foreach (DataRow dr in dt.Rows)
{
//Do what you need to do with your data here
}
}
}
}
Note: I don't have an environment to test this in (One with Office installed) so I can't say if it will work in your environment or not but I don't see why it shouldn't work.
<script type="text/javascript">
function getURLParameter(name) {
return decodeURIComponent(
(location.search.toLowerCase().match(RegExp("[?|&]" + name + '=(.+?)(&|$)')) || [, null])[1]
);
}
</script>
getURLParameter(id)
or getURLParameter(Id)
Works the same : )
If your app code base is large and you have multiple modules then you can try Local AAR approach as described here, it will give you a big boost in Android Studio performance.
Sample project can be found here:
.NET has spoiled us :) Your declaration is not valid for VBA.
Only constants can be given a value upon application load. You declare them like so:
Public Const APOSTROPHE_KEYCODE = 222
Here's a sample declaration from one of my vba projects:
If you're looking for something where you declare a public variable and then want to initialize its value, you need to create a Workbook_Open sub and do your initialization there. Example:
Private Sub Workbook_Open()
Dim iAnswer As Integer
InitializeListSheetDataColumns_S
HideAllMonths_S
If sheetSetupInfo.Range("D6").Value = "Enter Facility Name" Then
iAnswer = MsgBox("It appears you have not yet set up this workbook. Would you like to do so now?", vbYesNo)
If iAnswer = vbYes Then
sheetSetupInfo.Activate
sheetSetupInfo.Range("D6").Select
Exit Sub
End If
End If
Application.Calculation = xlCalculationAutomatic
sheetGeneralInfo.Activate
Load frmInfoSheet
frmInfoSheet.Show
End Sub
Make sure you declare the sub in the Workbook Object itself:
This should do it:
UPDATE ProductReviews
SET ProductReviews.status = '0'
FROM ProductReviews
INNER JOIN products
ON ProductReviews.pid = products.id
WHERE ProductReviews.id = '17190'
AND products.shopkeeper = '89137'
If you turn db.js
into a module you can require it from db_init.js
and just: node db_init.js
.
db.js:
module.exports = {
method1: function () { ... },
method2: function () { ... }
}
db_init.js:
var db = require('./db');
db.method1();
db.method2();
I hope this helps someone. I use this bit of logic to verify if network shares are responsive before checking the individual paths. It should handle DNS names and IP addresses
A valid path in the text file would be \192.168.1.2\'folder' or \NAS\'folder'
@echo off
title Network Folder Check
pushd "%~dp0"
:00
cls
for /f "delims=\\" %%A in (Files-to-Check.txt) do set Server=%%A
setlocal EnableDelayedExpansion
ping -n 1 %Server% | findstr TTL= >nul
if %errorlevel%==1 (
ping -n 1 %Server% | findstr "Reply from" | findstr "time" >nul
if !errorlevel!==1 (echo Network Asset %Server% Not Found & pause & goto EOF)
)
:EOF
I might have a simple answer for the question without extending the TextView and implementing a long code.
Code :
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf"));
Place the custom font file in assets folder as usual and try this. It works for me. I just dont understand why peter has given such a huge code for this simple thing or he has given his answer in old version.
I tried all of those above answers, and I then summarized a pipeline of how to draw the fixed-axes image. It applied both to show
function and savefig
function.
before you plot:
fig = pylab.figure()
ax = fig.gca()
ax.set_autoscale_on(False)
This is to request an ax
which is subplot(1,1,1)
.
During the plot:
ax.plot('You plot argument') # Put inside your argument, like ax.plot(x,y,label='test')
ax.axis('The list of range') # Put in side your range [xmin,xmax,ymin,ymax], like ax.axis([-5,5,-5,200])
After the plot:
To show the image :
fig.show()
To save the figure :
fig.savefig('the name of your figure')
I find out that put axis
at the front of the code won't work even though I have set autoscale_on
to False
.
I used this code to create a series of animation. And below is the example of combing multiple fixed axes images into an animation.
With FluidXML you can generate and store an XML document very easily.
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);
The meaning of this exception is explained here: https://bz.apache.org/bugzilla/show_bug.cgi?id=27829
Summary: Java dies, Tomcat shut down hook is called, exception is thrown.
So if a firewall prevents the shutdown message from reaching Tomcat, Java will eventually die first (ex during system reboot/shutdown), and the exception will appear.
There are other possibilities.
In my case, my problem had something to do with my initscript (Linux) being incorrectly installed. That implied Java was getting killed by the OS during shutdown/reboot and not as a result of the script. The solution as simple as this:
chkconfig --del initscript
chkconfig --add initscript
Before the fix I had the following in rc.d:
find /etc/rc.d | grep initscript | sort
/etc/rc.d/init.d/initscript
/etc/rc.d/rc2.d/S85initscript
/etc/rc.d/rc3.d/S85initscript
/etc/rc.d/rc4.d/S85initscript
/etc/rc.d/rc5.d/S85initscript
After the fix:
find /etc/rc.d | grep initscript | sort
/etc/rc.d/init.d/initscript
/etc/rc.d/rc0.d/K15initscript
/etc/rc.d/rc1.d/K15initscript
/etc/rc.d/rc2.d/K15initscript
/etc/rc.d/rc3.d/K15initscript
/etc/rc.d/rc4.d/K15initscript
/etc/rc.d/rc5.d/S85initscript
/etc/rc.d/rc6.d/K15initscript
Conclusion: if you get this exception, make sure Tomcat is shutdown properly, not as a result of Java being terminated. Check your firewall, shutdown scripts etc.
If Subversion is already installed ,there's no need to reinstall it with the command line client tools.
Simply Goto
Start(Rightclick) ->App and Feature ->TortoiseSvn->Modify->Install command line client tools.
You can also use strcspn(string, "e")
but this may be much slower since it's able to handle searching for multiple possible characters. Using strchr
and subtracting the pointer is the best way.
(1) Your <script>
tag should be placed before the closing </body>
tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
If you want to look for all commits by filename
and not by filepath
, use:
git log --all -- '*.wmv'
Folks above hit the right notes for storage, though if you also need to consider any PII data that needs to be stored then you can also stash into the keychain using something like https://github.com/oblador/react-native-keychain since ASyncStorage is unencrypted. It can be applied as part of the persist configuration in something like redux-persist.
$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
$url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}
I think you missed a key point in the documentation for .add()
Mutates the original moment by adding time.
You appear to be treating it as a function that returns the immutable result. Easy mistake to make. :)
If you use the return value, it is the same actual object as the one you started with. It's just returned as a convenience for method chaining.
You can work around this behavior by cloning the moment, as described here.
Also, you cannot just use ==
to test. You could format each moment to the same output and compare those, or you could just use the .isSame()
method.
Your code is now:
var timestring1 = "2013-05-09T00:00:00Z";
var timestring2 = "2013-05-09T02:00:00Z";
var startdate = moment(timestring1);
var expected_enddate = moment(timestring2);
var returned_endate = moment(startdate).add(2, 'hours'); // see the cloning?
returned_endate.isSame(expected_enddate) // true
If you are using Json.Net attribute [JsonIgnore]
will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
I ran $hadoop namenode
to start namenode manually at foreground.
From the logs I figured out that 50070 is ocuupied, which was defaultly used by dfs.namenode.http-address. After configuring dfs.namenode.http-address in hdfs-site.xml, everything went well.
See the below example
CREATE TABLE users (
-- make the "id" column a primary key; this also creates
-- a UNIQUE constraint and a b+-tree index on the column
id SERIAL PRIMARY KEY,
name TEXT,
age INT4
);
INSERT INTO users (name, age) VALUES ('Mozart', 20);
Then for getting last inserted id use this for table "user" seq column name "id"
SELECT currval(pg_get_serial_sequence('users', 'id'));
I had this same issue, and running script in robomongo (Robo 3T 1.1.1) also doesn't allow to copy values and there was no export option either. The best way I could achieve this is to use mongoexport, if mongodb is installed on your local, you can use mongoexport to connect to database on any server and extract data
To connect to Data on remote server, and csv output file, run the following mongoexport in your command line
mongoexport --host HOSTNAME --port PORT --username USERNAME --password "PASSWORD" --collection COLLECTION_NAME --db DATABASE_NAME --out OUTPUTFILE.csv --type=csv --fieldFile fields.txt
fieldFile: helps to extract the desired columns, ex: contents of fields.txt can be just:
userId
to only extract values of the column 'userId'
Data on remote server, json output file:
mongoexport --host HOST_NAME --port PORT --username USERNAME --password "PASSWORD" --collection COLECTION_NAME --db DATABASE_NAME --out OUTPUT.json
this extracts all fields into the json file
data on localhost (mongodb should be running on localhost)
mongoexport --db DATABASE_NAME --collection COLLECTION --out OUTPUT.json
Reference: https://docs.mongodb.com/manual/reference/program/mongoexport/#use
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
Some googling led me to the following post:
http://www.developerweb.net/forum/showthread.php?t=3434
The code provided in the post is in C, but it shouldn't be too hard to rewrite it to Java.
Note here i am using custom cell this code is perfectly working for me
@IBAction func call(sender: UIButton)
{
var contentView = sender.superview;
var cell = contentView?.superview as EmployeeListCustomCell
if (!(cell.isKindOfClass(EmployeeListCustomCell)))
{
cell = (contentView?.superview)?.superview as EmployeeListCustomCell
}
let phone = cell.lblDescriptionText.text!
//let phone = detailObject!.mobile!
let url:NSURL = NSURL(string:"tel://"+phone)!;
UIApplication.sharedApplication().openURL(url);
}
Easier way for me is to switch to R1C1
notation and just use R[-1]C1
and switch back when done.
First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.
Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).
The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)
The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.
An other example would be on the "created_on" column where you want to let the database handle the date creation
See the javadoc. It's an inclusive index for the first argument and exclusive for the second.
You can use php built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change filed name as your requirement
then the result is
and if you want to concat same filed using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
I had the same problem on XAMPP for Windows when I try to install composer.
I did php -v
and php throwing error :
Unable to load dynamic library '/xampp/php/ext/php_bz2.dll'
It took me a while until I realized that I need to setup my XAMPP. So I run setup_xampp.bat
and php return to works like a charm.
Fwiw, I downloaded the standard Java EE version of the Mars version of Eclipse, and ran into the same deal -- didn't see a Web option if I tried File >>> New >>> Project wizard.
The good news: Probably no extra installation needed.
It looks like what I wanted was to select the Other
option rather than the Project
item (strangely this is what comes up when you hit Ctrl-N, but that also lets us know we're probably on the right track):
After you select "Other", you'll see the "Select a wizard" screen, where you can select "Dynamic Web Project" and profit.
I realise this is an old post but I was trying to work something out for my site to have a sidebar. Would this work?
#sidebar-background
{
position:fixed;
width:250px;
top:0;
bottom:0;
background-color:orange;
}
#content-background
{
position:fixed;
right:0;
top:0;
bottom:0;
left:250px;
background-color:pink;
}
#sidebar
{
float:left;
width:250px;
}
#content
{
float:left;
width:600px;
}
<div id="sidebar-background"></div>
<div id="content-background"></div>
<div id="sidebar">Sidebar stuff here</div>
<div id="content">Stuff in here</div>
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
You need mask
:
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
Another solution with loc
and boolean indexing
:
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
Sample:
import pandas as pd
import numpy as np
sample = pd.DataFrame({'PR':[10,100,40] })
print (sample)
PR
0 10
1 100
2 40
sample['PR'] = sample['PR'].mask(sample['PR'] < 90, np.nan)
print (sample)
PR
0 NaN
1 100.0
2 NaN
sample.loc[sample['PR'] < 90, 'PR'] = np.nan
print (sample)
PR
0 NaN
1 100.0
2 NaN
EDIT:
Solution with apply
:
sample['PR'] = sample['PR'].apply(lambda x: np.nan if x < 90 else x)
Timings len(df)=300k
:
sample = pd.concat([sample]*100000).reset_index(drop=True)
In [853]: %timeit sample['PR'].apply(lambda x: np.nan if x < 90 else x)
10 loops, best of 3: 102 ms per loop
In [854]: %timeit sample['PR'].mask(sample['PR'] < 90, np.nan)
The slowest run took 4.28 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 3.71 ms per loop
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
You could give bluefish a try. Has a bunch of nice features for website work. Syntax files for most every language.
http://bluefish.openoffice.nl/
If on windows give Crimson Editor a try http://www.crimsoneditor.com/ It's been a long while since I ran windows, but iirc, 'official' development has stopped on it, but the community has taken up a fork of it and called it emerald or somesuch. Crimson editor is still very capable as is.
Both bluefish and crimson editor have project management abilities. FTP ablilities, macros etc etc
Kingfisher is one of the best library for load image into URL.
Github URL - https://github.com/onevcat/Kingfisher
// If you want to use Activity Indicator.
imageview_pic.kf.indicatorType = .activity
imageview_pic.kf.setImage(with: URL(string: "Give your url string"))
// If you want to use custom placeholder image.
imageview_pic.kf.setImage(with: URL(string: "Give your url string"), placeholder: UIImage(named: "placeholder image name"), options: nil, progressBlock: nil, completionHandler: nil)
First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local
.
Another simple way is to use @reboot
in your crontab. Read the cron manpage for details.
However, if you want to do things properly, in addition to adding a script to /etc/init.d
you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d
which creates a symlink from some of the /etc/rc*
directories to your script. So, you'd need to do something like:
update-rc.d yourscriptname start 2
However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README
has some details and further pointers.
Using file:///// just doesn't work if security settings are set to even a moderate level.
If you just want users to be able to download/view files* located on a network or share you can set up a Virtual Directory in IIS. On the Properties tab make sure the "A share located on another computer" is selected and the "Connect as..." is an account that can see the network location.
Link to the virtual directory from your webpage (e.g. http://yoursite/yourvirtualdir/) and this will open up a view of the directory in the web browser.
*You can allow write permissions on the virtual directory to allow users to add files but not tried it and assume network permissions would override this setting.
Try this, it works for me:
var storage = null;
setLocalStorage();
function setLocalStorage() {
storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));
try {
storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
}
catch (e) {
if (e.name == "NS_ERROR_FILE_CORRUPTED") {
storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
}
}
}
example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.
import time
import threading
def t():
with open('/dev/urandom') as f:
for x in xrange(100):
f.read(4 * 65535)
if __name__ == '__main__':
start_time = time.time()
t()
t()
t()
t()
print "Sequential run time: %.2f seconds" % (time.time() - start_time)
start_time = time.time()
t1 = threading.Thread(target=t)
t2 = threading.Thread(target=t)
t3 = threading.Thread(target=t)
t4 = threading.Thread(target=t)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print "Parallel run time: %.2f seconds" % (time.time() - start_time)
result:
$ python 1.py
Sequential run time: 3.69 seconds
Parallel run time: 4.82 seconds
Since Android Studio V1.0 the jar file is available inside the following project link:
debug ver: "your_app"\build\intermediates\bundles\debug\classes.jar
release ver: "your_app"\build\intermediates\bundles\release\classes.jar
The JAR file is created on the build procedure, In Android Studio GUI it's from Build->Make Project and from CMD line it's "gradlew build".
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
dynamic_cast
only supports pointer and reference types. It returns NULL
if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast
can be used to check if an object is of a given type, static_cast
cannot (you will simply end up with an invalid value).
C-style (and other) casts have been covered in the other answers.
Adding on to the other answers, you can check the OS and decide whether to use "-c" or "-n":
import os, platform
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if platform.system().lower()=="windows" else "-c 1 ") + host)
This will work on Windows, OS X, and Linux
You can also use sys
:
import os, sys
host = "8.8.8.8"
os.system("ping " + ("-n 1 " if sys.platform().lower()=="win32" else "-c 1 ") + host)
Please define brightness. If you're looking for how close to white the color is you can use Euclidean Distance from (255, 255, 255)
Look here: http://www.w3schools.com/tags/tag_p.asp
The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.
you could remove the extra space by using css
p {
margin: 0px;
padding: 0px;
}
or use the element <span>
which has no default margins and is an inline element.
Another option with Filter
Filter(function(x) !all(is.na(x)), df)
NOTE: Data from @Simon O'Hanlon's post.
For 2D matrix:
mat.rows – Number of rows in a 2D array.
mat.cols – Number of columns in a 2D array.
Or: C++: Size Mat::size() const
The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).
For multidimensional matrix, you need to use
int thisSizes[3] = {2, 3, 4};
cv::Mat mat3D(3, thisSizes, CV_32FC1);
// mat3D.size tells the size of the matrix
// mat3D.size[0] = 2;
// mat3D.size[1] = 3;
// mat3D.size[2] = 4;
Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
While Dictionary is implemented as a hash table, SortedDictionary is implemented as a Red-Black Tree.
If you don't take advantage of the order in your algorithm and only need to sort the data before output, using SortedDictionary would have negative impact on performance.
You can "sort" the dictionary like this:
Dictionary<string, int> dictionary = new Dictionary<string, int>();
// algorithm
return new SortedDictionary<string, int>(dictionary);
Using /proc/tty/drivers only indicates which tty drivers are loaded. If you're looking for a list of the serial ports check out /dev/serial, it will have two subdirectories: by-id and by-path.
EX:
# find . -type l
./by-path/usb-0:1.1:1.0-port0
./by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0
Thanks to this post: https://superuser.com/questions/131044/how-do-i-know-which-dev-ttys-is-my-serial-port
Enter the original date into a Date
object and then print out the result with a DateFormat
. You may have to split up the string into smaller pieces to create the initial Date
object, if the automatic parse method does not accept your format.
Pseudocode:
Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);
You will need to use strip()
because of the extra bits in the strings.
A2 = [float(x.strip('"')) for x in A1]
This solution uses nothing but standard .NET calls.
Tested:
Reference:
// Add a Reference to the assembly System.Web
Code:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
private async Task<WebResponse> CallUri(string url, TimeSpan timeout)
{
var uri = new Uri(url);
NameValueCollection rawParameters = HttpUtility.ParseQueryString(uri.Query);
var parameters = new Dictionary<string, string>();
foreach (string p in rawParameters.Keys)
{
parameters[p] = rawParameters[p];
}
var client = new HttpClient { Timeout = timeout };
HttpResponseMessage response;
if (parameters.Count == 0)
{
response = await client.GetAsync(url);
}
else
{
var content = new FormUrlEncodedContent(parameters);
string urlMinusParameters = uri.OriginalString.Split('?')[0]; // Parameters always follow the '?' symbol.
response = await client.PostAsync(urlMinusParameters, content);
}
var responseString = await response.Content.ReadAsStringAsync();
return new WebResponse(response.StatusCode, responseString);
}
private class WebResponse
{
public WebResponse(HttpStatusCode httpStatusCode, string response)
{
this.HttpStatusCode = httpStatusCode;
this.Response = response;
}
public HttpStatusCode HttpStatusCode { get; }
public string Response { get; }
}
To call with no parameters (uses a "GET" behind the scenes):
var timeout = TimeSpan.FromSeconds(300);
WebResponse response = await this.CallUri("http://www.google.com/", timeout);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
Console.Write(response.Response); // Print HTML.
}
To call with parameters (uses a "POST" behind the scenes):
var timeout = TimeSpan.FromSeconds(300);
WebResponse response = await this.CallUri("http://example.com/path/to/page?name=ferret&color=purple", timeout);
if (response.HttpStatusCode == HttpStatusCode.OK)
{
Console.Write(response.Response); // Print HTML.
}
You may have used built-in name 'list' for a variable in your code. If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal. In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.
To do it in PHP: You have a couple of parameters to view your page, lets say action
and view-all
. You will (probably) access these already with $action = $_GET['action']
or whatever, maybe setting a default value.
Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'
.
And in the end you just build the url with these values again like
$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;
And thats it.
So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).
I think that using colnames
and rownames
makes the most sense; here's why.
Using names
has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames
whenever you use matrices. By calling colnames
, you only have to remember one function. Finally, if you look at the code for colnames
, you will see that it calls names
in the case of a data frame anyway, so the output is identical.
rownames
and row.names
return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames
will print "NULL" (as does colnames
), but row.names
returns it invisibly. Since there isn't much to choose between the two functions, rownames
wins on the grounds of aesthetics, since it pairs more prettily withcolnames
. (Also, for the lazy programmer, you save a character of typing.)
Using a #t=10,20
fragment worked for me.
Adding a bit to use Gokhan's solution for using:
--allow-file-access-from-files
Now you just need to append above text in Target text followed by a space. make sure you close all the instances of chrome browser after adding above property. Now restart chrome by the icon where you added this property. It should work for all.
Since the usage of lambda was asked in the context of sorted()
, take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions
It's working in 2021,
Though the Repo has to be made private first then the click on
settings => Manage access => Invite Collaborator
The user who gets the repo access has to navigate to the repo and can make changes to the main branch.
Just want to reiterate this will work in pandas >= 0.9.1:
In [2]: read_csv('sample.csv', dtype={'ID': object})
Out[2]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
I'm creating an issue about detecting integer overflows also.
EDIT: See resolution here: https://github.com/pydata/pandas/issues/2247
Update as it helps others:
To have all columns as str, one can do this (from the comment):
pd.read_csv('sample.csv', dtype = str)
To have most or selective columns as str, one can do this:
# lst of column names which needs to be string
lst_str_cols = ['prefix', 'serial']
# use dictionary comprehension to make dict of dtypes
dict_dtypes = {x : 'str' for x in lst_str_cols}
# use dict on dtypes
pd.read_csv('sample.csv', dtype=dict_dtypes)
Call and apply both are used to force the this
value when a function is executed. The only difference is that call
takes n+1
arguments where 1 is this
and 'n' arguments
. apply
takes only two arguments, one is this
the other is argument array.
The advantage I see in apply
over call
is that we can easily delegate a function call to other function without much effort;
function sayHello() {
console.log(this, arguments);
}
function hello() {
sayHello.apply(this, arguments);
}
var obj = {name: 'my name'}
hello.call(obj, 'some', 'arguments');
Observe how easily we delegated hello
to sayHello
using apply
, but with call
this is very difficult to achieve.
I believe what you are looking for is "git restore".
The easiest way is to remove the file locally, and then execute the git restore command for that file:
$ rm file.txt
$ git restore file.txt
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
If you want to concatenate the fields using / as a separator, you can use concat_ws
:
select concat_ws('/', col1, col2, col3) from mytable
You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.
A simple way is to use tail(-n) to remove the first n rows
df=df.tail(-3)
I came up with this.This seems to work best for me.It converts a string of number and splits it into array of integer:
void splitInput(int arr[], int sizeArr, char num[])
{
for(int i = 0; i < sizeArr; i++)
// We are subtracting 48 because the numbers in ASCII starts at 48.
arr[i] = (int)num[i] - 48;
}
Resin 3.0 documents this behavior:
load-on-startup can specify an (optional) integer value. If the value is 0 or greater, it indicates an order for servlets to be loaded, servlets with higher numbers get loaded after servlets with lower numbers.
The JSP 3.1 spec (JSR 340) says this on page 14-160:
The element
load-on-startup
indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the Web application. The element content of this element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the sameload-on-startup
value.
You probably want to check not only the JSR, but also the documentation for your web container. There may be differences
The following resolved the issue:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String str = "4*5";
System.out.println(engine.eval(str));
You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.
to set RichTextBox text:
richTextBox1.Document.Blocks.Clear();
richTextBox1.Document.Blocks.Add(new Paragraph(new Run("Text")));
to get RichTextBox text:
string richText = new TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd).Text;
I had a similar problem and I solved it by setting a static IP on the Android device.
When you add the network on Android, first you enter the SSID and password, then underneath you can open advanced options and set a static IP.
The following example demonstrates how to POST a JSON via WebClient.UploadString Method:
var vm = new { k = "1", a = "2", c = "3", v= "4" };
using (var client = new WebClient())
{
var dataString = JsonConvert.SerializeObject(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}
Prerequisites: Json.NET library
If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.
Taken from Mathematics in Python:
class Vector:
def __init__(self, data):
self.data = data
def __repr__(self):
return repr(self.data)
def __add__(self, other):
data = []
for j in range(len(self.data)):
data.append(self.data[j] + other.data[j])
return Vector(data)
x = Vector([1, 2, 3])
print x + x
A nonblocking call returns immediately with whatever data are available: the full number of bytes requested, fewer, or none at all.
An asynchronous call requests a transfer that will be performed in its whole(entirety) but will complete at some future time.
Since Java 1.5 you can use the String.format
method. For example, to do the same thing as your example:
String format = String.format("%0%d", digits);
String result = String.format(format, num);
return result;
In this case, you're creating the format string using the width specified in digits, then applying it directly to the number. The format for this example is converted as follows:
%% --> %
0 --> 0
%d --> <value of digits>
d --> d
So if digits is equal to 5, the format string becomes %05d
which specifies an integer with a width of 5 printing leading zeroes. See the java docs for String.format
for more information on the conversion specifiers.
let el = document.querySelector('#el');
if (el.hasChildNodes()) {
el.childNodes.forEach(child => el.removeChild(child));
}
I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel
wasn’t installed in the virtualenv.
You can just read from stdin unless the user supply a filename ?
If not, treat the special "filename" -
as meaning "read from stdin". The user would have to start the program like cat file | myprogram -
if he wants to pipe data to it, and myprogam file
if he wants it to read from a file.
int main(int argc,char *argv[] ) {
FILE *input;
if(argc != 2) {
usage();
return 1;
}
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"rb");
//check for errors
}
If you're on *nix, you can check whether stdin is a fifo:
struct stat st_info;
if(fstat(0,&st_info) != 0)
//error
}
if(S_ISFIFO(st_info.st_mode)) {
//stdin is a pipe
}
Though that won't handle the user doing myprogram <file
You can also check if stdin is a terminal/console
if(isatty(0)) {
//stdin is a terminal
}
On the model set $incrementing
to false
public $incrementing = false;
This will stop it from thinking it is an auto increment field.
Not sure if this would have a faster computational time, but another option...
$acceptedFormats = array('gif', 'png', 'jpg');
if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
echo 'error';
}
Choose dlib .whl file according to your installed python version. For example if installed python version is 3.6.7 , 64bit system or if python is 3.5.0 32 bit then choose dlib-19.5.1-cp36-cp36m-win_amd64.whl and dlib-18.17.100-cp35-none-win32.whl respectively.
Bolded text says the python supporting version.
Download wheel file from here or copy the link address
pip install dlib-19.5.1-cp36-cp36m-win_amd64.whl
for above method .whl file shoud be in the working directory
or
Below link for python3.6 supporting dlib link, for python 3.5 u can replace with dlib 35.whl link
pip install https://files.pythonhosted.org/packages/24/ea/81e4fc5b978277899b1c1a63ff358f1f645f9369e59d9b5d9cc1d57c007c/dlib-19.5.1-cp36-cp36m-win_amd64.whl#sha256=7739535b76eb40cbcf49ba98d894894d06ee0b6e8f18a25fef2ab302fd5401c7
Right click on your project folder (Maven one), select properties and from the properties window, again select Java Compiler and see what is selected against compiler compliance level and make sure that it is the same version as your jre. In my case I had 1.8 but 1.5 was selected against compiler compliance level. After selecting 1.8 the build was successful without this error.
Thanks to all for sharing your answers and examples. The same standalone program worked for me by small changes and adding the lines of code below.
In this case, keystore file was given by webservice provider.
// Small changes during connection initiation..
// Please add this static block
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{ @Override
public boolean verify(String hostname, SSLSession arg1) {
// TODO Auto-generated method stub
if (hostname.equals("X.X.X.X")) {
System.out.println("Return TRUE"+hostname);
return true;
}
System.out.println("Return FALSE");
return false;
}
});
}
String xmlServerURL = "https://X.X.X.X:8080/services/EndpointPort";
URL urlXMLServer = new URL(null,xmlServerURL,new sun.net.www.protocol.https.Handler());
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlXMLServer .openConnection();
// Below extra lines are added to the same program
//Keystore file
System.setProperty("javax.net.ssl.keyStore", "Drive:/FullPath/keystorefile.store");
System.setProperty("javax.net.ssl.keyStorePassword", "Password"); // Password given by vendor
//TrustStore file
System.setProperty("javax.net.ssl.trustStore"Drive:/FullPath/keystorefile.store");
System.setProperty("javax.net.ssl.trustStorePassword", "Password");
if "ABCD" in "xxxxABCDyyyy":
# whatever
create table demo ( id int, ts timestamp )
insert into demo(id,ts) values (1, DEFAULT)
For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.
What you should do is to catch the Enter key at form level. Add this code to the form:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
{
//do something
return true;
}
else
{
return base.ProcessCmdKey(ref msg, keyData);
}
}
Quoting Yoga...
For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/
I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...
/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml
...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.
print(string ("Yo!"));
You need to make a (temporary) std::string
object out of it.
First of all, if you want it displayed on a PHP form, the medium is HTML and so a new line will be rendered with the <br />
tag. Check the source HTML of the page - you may possibly have the new line rendered just as a line break, in which case your problem is simply one of translating the text for output to a web browser.
I had to connect to VPN for the publish script to successfully deploy to the DB.
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
Its works for me.
tv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
your fadeIn()
function calls the fadeOut()
function, which calls the fadeIn()
function again. the recursion is in the JS.
to set unlimited number of rows use
None
i.e.,
pd.set_option('display.max_cols', None)
now the notebook will display all the rows in all datasets within the notebook ;)
Similarly you can set to show all columns as
pd.set_option('display.max_rows', None)
now if you use run the cell with only dataframe with out any head or tail tags as
df
then it will show all the rows and columns in the dataframe df
This solution is much simpler and generic, for both 'file name' and 'path'.
const str = 'C:\\Documents and Settings\\img\\recycled log.jpg';
// regex to split path to two groups '(.*[\\\/])' for path and '(.*)' for file name
const regexPath = /^(.*[\\\/])(.*)$/;
// execute the match on the string str
const match = regexPath.exec(str);
if (match !== null) {
// we ignore the match[0] because it's the match for the hole path string
const filePath = match[1];
const fileName = match[2];
}
A little slower, but readable I think:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
Well, the error message says it all: NumPy arrays do not have an append()
method. There's a free function numpy.append()
however:
numpy.append(M, a)
This will create a new array instead of mutating M
in place. Note that using numpy.append()
involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.
brew install cask
brew cask install xquartz
brew tap homebrew/science
brew install r
This way, everything is packager managed, so there's no need to manually download and install anything.
just goto
Tools > Options > Keymaps
than searchzoom
click on three (...
) dot and click Edit
press
your_shortcut_keys
( what ever shortcut you want to set)
It's Magic is it's ability to reduce having to write code for every Variable Type passed into specific functions. Consider a Python similar print() function in it's C base.
#include <iostream>
#include <string>
#include <array>
using namespace std;
void print(auto arg) {
cout<<arg<<" ";
}
int main()
{
string f = "String";//tok assigned
int x = 998;
double a = 4.785;
string b = "C++ Auto !";
//In an opt-code ASCII token stream would be iterated from tok's as:
print(a);
print(b);
print(x);
print(f);
}
If you really want to use linq, you can do something like this
li= (from tl in li
select new Myclass
{
name = tl.name,
age = (tl.name == "di" ? 10 : (tl.name == "marks" ? 20 : 30))
}).ToList();
or
li = li.Select(ex => new MyClass { name = ex.name, age = (ex.name == "di" ? 10 : (ex.name == "marks" ? 20 : 30)) }).ToList();
This assumes that there are only 3 types of name
. I would externalize that part into a function to make it more manageable.
This is more of an important comment. Sharing references of sytanx that is acceptable out of the box. For hack solutions look at other answers.
Per Apple's docs, Action Method Definitions have to be either one of these three. Anything else is unaccepted.
@IBAction func doSomething()
@IBAction func doSomething(sender: UIButton)
@IBAction func doSomething(sender: UIButton, forEvent event: UIEvent)
Here sed
is replacing all occurrences of %
with $
in its standard input.
As an example
$ echo 'foo%bar%' | sed -e 's,%,$,g'
will produce "foo$bar$".
This is all you have to do:
In front.inc
global $name;
$name = 'james';
WSDL act as an interface between sender and receiver.
SOAP message is request and response in xml format.
comparing with java RMI
WSDL is the interface class
SOAP message is marshaled request and response message.
In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client-server architecture in which, the presentation, the application processing and the data management are logically separate processes. For example, an application that uses middleware to service data requests between a user and a database employs multi-tier architecture. The most widespread use of "multi-tier architecture" refers to three-tier architecture.
It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you can host logical tier and database on the same box.
Edit: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.
For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's DataSet class or Web Services protocol like SOAP are few of such attempts to fly objects over the wire.
Try this:
find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;
In case you need short unique IDs as your filename, try shortuuid
, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22
compared to
>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
Had this issue again just now, and believe it or not, all I had to do was close the developer tools. Apparently the Console tab has the focus priority over the page content.
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
Although it doesn't really answers this specific question. Others got the same error message with this mistake.
For those who like me initial forgot the -r
: Use pip install -r requirements.txt
the -r
is essential for the command.
The original answer:
Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args]
.
Of course this assumes that .NET is installed on the target machine.
Here's the code. Feel free to copy!
using System;
using System.Diagnostics;
using System.Text;
namespace dotNetLauncher
{
class Program
{
/*
If you make .NET Core applications, they have to be launched like .NET blah.dll args here
This is a convenience EXE file that launches .NET Core applications via name.exe
Just rename the output exe to the name of the .NET Core DLL file you wish to launch
*/
static void Main(string[] args)
{
var exePath = AppDomain.CurrentDomain.BaseDirectory;
var exeName = AppDomain.CurrentDomain.FriendlyName;
var assemblyName = exeName.Substring(0, exeName.Length - 4);
StringBuilder passInArgs = new StringBuilder();
foreach(var arg in args)
{
bool needsSurroundingQuotes = false;
if (arg.Contains(" ") || arg.Contains("\""))
{
passInArgs.Append("\"");
needsSurroundingQuotes = true;
}
passInArgs.Append(arg.Replace("\"","\"\""));
if (needsSurroundingQuotes)
{
passInArgs.Append("\"");
}
passInArgs.Append(" ");
}
string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";
var p = new Process
{
StartInfo = new ProcessStartInfo("dotnet", callingArgs)
{
UseShellExecute = false
}
};
p.Start();
p.WaitForExit();
}
}
}
I did it this way:
db.collection.aggregate([
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
print(index);
});
The aggregate will return the array so just loop it and get the final index .
And other way of doing it is:
var count = 0 ;
db.collection.aggregate([
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } }
] ).map(function(record, index){
count++
});
print(count);
This is a generic solution.
startdayvalue is day number of start date.
weekendday_1 is day numner of week end.
day number - MON - 1, TUE - 2, ... SAT - 6, SUN -7.
difference is difference between two dates..
Example : Start Date : 4 April, 2013, End Date : 14 April, 2013
Difference : 10, startdayvalue : 4, weekendday_1 : 7 (if SUNDAY is a weekend for you.)
This will give you number of holidays.
No of business day = (Difference + 1) - holiday1
if (startdayvalue > weekendday_1)
{
if (difference > ((7 - startdayvalue) + weekendday_1))
{
holiday1 = (difference - ((7 - startdayvalue) + weekendday_1)) / 7;
holiday1 = holiday1 + 1;
}
else
{
holiday1 = 0;
}
}
else if (startdayvalue < weekendday_1)
{
if (difference > (weekendday_1 - startdayvalue))
{
holiday1 = (difference - (weekendday_1 - startdayvalue)) / 7;
holiday1 = holiday1 + 1;
}
else if (difference == (weekendday_1 - startdayvalue))
{
holiday1 = 1;
}
else
{
holiday1 = 0;
}
}
else
{
holiday1 = difference / 7;
holiday1 = holiday1 + 1;
}
java.time.Instant // Represent a moment as seen in UTC. Internally, a count of nanoseconds since 1970-01-01T00:00Z.
.ofEpochSecond( 1_220_227_200L ) // Pass a count of whole seconds since the same epoch reference of 1970-01-01T00:00Z.
People use various precisions in tracking time as a number since an epoch. So when you obtain some numbers to be interpreted as a count since an epoch, you must determine:
In your case, as others noted, you seem to have been given seconds since the Unix epoch. But you are passing those seconds to a constructor that expects milliseconds. So the solution is to multiply by 1,000.
Lessons learned:
Your data seems to be in whole seconds. If we assume an epoch of the beginning of 1970, and if we assume UTC time zone, then 1,220,227,200
is the first moment of the first day of September 2008.
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use instead either the Joda-Time library or the new java.time package bundled in Java 8 (and inspired by Joda-Time).
Note that unlike j.u.Date, a DateTime
in Joda-Time truly knows its own assigned time zone. So in the example Joda-Time 2.4 code seen below, note that we first parse the milliseconds using the default assumption of UTC. Then, secondly, we assign a time zone of Paris to adjust. Same moment in the timeline of the Universe, but different wall-clock time. For demonstration, we adjust again, to UTC. Almost always better to explicitly specify your desired/expected time zone rather than rely on an implicit default (often the cause of trouble in date-time work).
We need milliseconds to construct a DateTime. So take your input of seconds, and multiply by a thousand. Note that the result must be a 64-bit long
as we would overflow a 32-bit int
.
long input = 1_220_227_200L; // Note the "L" appended to long integer literals.
long milliseconds = ( input * 1_000L ); // Use a "long", not the usual "int". Note the appended "L".
Feed that count of milliseconds to constructor. That particular constructor assumes the count is from the Unix epoch of 1970. So adjust time zone as desired, after construction.
Use proper time zone names, a combination of continent and city/region. Never use 3 or 4 letter codes such as EST
as they are neither standardized not unique.
DateTime dateTimeParis = new DateTime( milliseconds ).withZone( DateTimeZone.forID( "Europe/Paris" ) );
For demonstration, adjust the time zone again.
DateTime dateTimeUtc = dateTimeParis.withZone( DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeParis.withZone( DateTimeZone.forID( "America/Montreal" ) );
Dump to console. Note how the date is different in Montréal, as the new day has begun in Europe but not yet in America.
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeUTC: " + dateTimeUtc );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
When run.
dateTimeParis: 2008-09-01T02:00:00.000+02:00
dateTimeUTC: 2008-09-01T00:00:00.000Z
dateTimeMontréal: 2008-08-31T20:00:00.000-04:00
The makers of Joda-Time have asked us to migrate to its replacement, the java.time framework as soon as is convenient. While Joda-Time continues to be actively supported, all future development will be done on the java.time classes and their extensions in the ThreeTen-Extra project.
The java-time framework is defined by JSR 310 and built into Java 8 and later. The java.time classes have been back-ported to Java 6 & 7 on the ThreeTen-Backport project and to Android in the ThreeTenABP project.
An Instant
is a moment on the timeline in UTC with a resolution of nanoseconds. Its epoch is the first moment of 1970 in UTC.
Instant instant = Instant.ofEpochSecond( 1_220_227_200L );
Apply an offset-from-UTC ZoneOffset
to get an OffsetDateTime
.
Better yet, if known, apply a time zone ZoneId
to get a ZonedDateTime
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
In my case it worked great just by doing the following:
[HttpPost]
public ActionResult DoSomething(int custNum)
{
// Some magic code here...
}
<form id="frmSomething" method="post">
<div>
<!-- Some magic html here... -->
</div>
<button id="btnSubmit" type="submit">Submit</button>
</form>
var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
btnSubmit.click(function()
{
frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);
btnSubmit.submit();
});
Hope this helps vatos!
You could use the ViewCommand design pattern. It describes a method for the MVVM design pattern to control a View from a ViewModel with commands.
I've implemented it based on King A.Majid's suggestion to use the MVVM Light Messenger class. The ViewCommandManager class handles invoking commands in connected views. It's basically the other direction of regular Commands, for these cases when a ViewModel needs to do some action in its View. It uses reflection like data-bound commands and WeakReferences to avoid memory leaks.
http://dev.unclassified.de/source/viewcommand (also published on CodeProject)
You can use replace
instead of gsub
.
"hello _there_".replace(/_(.*?)_/g, "<div>\$1</div>")
Yes, you can select the data, calculate the difference, and insert all values in the other table:
insert into #temp2 (Difference)
select previous - Present
from #TEMP1
Given an instance of the struct, you set the values.
student thisStudent;
Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
thisStudent.s_id = int.Parse(Console.ReadLine());
thisStudent.s_name = Console.ReadLine();
thisStudent.c_name = Console.ReadLine();
thisStudent.s_dob = Console.ReadLine();
Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.
I also had problems using UpdateAsync when developing a version of SimpleSecurity that uses ASP.NET Identity. For example, I added a feature to do a password reset that needed to add a password reset token to the user information. At first I tried using UpdateAsync and it got the same results as you did. I ended up wrapping the user entity in a repository pattern and got it to work. You can look at the SimpleSecurity project for an example. After working with ASP.NET Identity more (documentation is still non-existent) I think that UpdateAsync just commits the update to the context, you still need to save the context for it to commit to the database.
I sort of fixed it by using the following code:
$("#editor").live('input paste',function(e){
if(e.target.id == 'editor') {
$('<textarea></textarea>').attr('id', 'paste').appendTo('#editMode');
$("#paste").focus();
setTimeout($(this).paste, 250);
}
});
Now I just need to store the caret location and append to that position then I'm all set... I think :)
The _id
field is always present unless you explicitly exclude it. Do so using the -
syntax:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Or explicitly via an object:
exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});
query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};
Usefetch
and innerHTML
to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
_x000D_
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
_x000D_
On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh
) and when executed as a sh
script:
[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh
Hello
World
I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n
happens in sh
).
However, i noticed that this same script would behave differently when executed with bash
and would print out Hello\nWorld
instead:
[bash]§ bash test-str.sh
Hello\nWorld
I've managed to get the desired output with bash
as follows:
[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"
Note the double quotes around $STR
. This behaves identically if saved and run as a bash
script.
The following also gives the desired output:
[bash]§ echo "Hello
> World"
The docs for Google Test 1.7 suggest:
"If you have a broken test that you cannot fix right away, you can add the DISABLED_ prefix to its name. This will exclude it from execution."
Examples:
// Tests that Foo does Abc.
TEST(FooTest, DISABLED_DoesAbc) { ... }
class DISABLED_BarTest : public ::testing::Test { ... };
// Tests that Bar does Xyz.
TEST_F(DISABLED_BarTest, DoesXyz) { ... }
public string FirstLetterToUpper(string str)
{
if (str == null)
return null;
if (str.Length > 1)
return char.ToUpper(str[0]) + str.Substring(1);
return str.ToUpper();
}
Old answer: This makes every first letter to upper case
public string ToTitleCase(string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
The problem is that the checkout takes place on a laptop and in this case subversion can not cope with the off-line synchronization. The problem is reproducable on an other laptop while on a desktop I have no problem checking out the same repository.
I hope this answer wil help you, it took me quite long to find out.
You can use str.split
by whitespace (default separator) and parameter expand=True
for DataFrame
with assign to new columns:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL']})
print (df)
row
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
df[['a','b']] = df['row'].str.split(n=1, expand=True)
print (df)
row a b
0 00000 UNITED STATES 00000 UNITED STATES
1 01000 ALABAMA 01000 ALABAMA
2 01001 Autauga County, AL 01001 Autauga County, AL
3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 01005 Barbour County, AL 01005 Barbour County, AL
Modification if need remove original column with DataFrame.pop
df[['a','b']] = df.pop('row').str.split(n=1, expand=True)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
What is same like:
df[['a','b']] = df['row'].str.split(n=1, expand=True)
df = df.drop('row', axis=1)
print (df)
a b
0 00000 UNITED STATES
1 01000 ALABAMA
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
If get error:
#remove n=1 for split by all whitespaces
df[['a','b']] = df['row'].str.split(expand=True)
ValueError: Columns must be same length as key
You can check and it return 4 column DataFrame
, not only 2:
print (df['row'].str.split(expand=True))
0 1 2 3
0 00000 UNITED STATES None
1 01000 ALABAMA None None
2 01001 Autauga County, AL
3 01003 Baldwin County, AL
4 01005 Barbour County, AL
Then solution is append new DataFrame
by join
:
df = pd.DataFrame({'row': ['00000 UNITED STATES', '01000 ALABAMA',
'01001 Autauga County, AL', '01003 Baldwin County, AL',
'01005 Barbour County, AL'],
'a':range(5)})
print (df)
a row
0 0 00000 UNITED STATES
1 1 01000 ALABAMA
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
df = df.join(df['row'].str.split(expand=True))
print (df)
a row 0 1 2 3
0 0 00000 UNITED STATES 00000 UNITED STATES None
1 1 01000 ALABAMA 01000 ALABAMA None None
2 2 01001 Autauga County, AL 01001 Autauga County, AL
3 3 01003 Baldwin County, AL 01003 Baldwin County, AL
4 4 01005 Barbour County, AL 01005 Barbour County, AL
With remove original column (if there are also another columns):
df = df.join(df.pop('row').str.split(expand=True))
print (df)
a 0 1 2 3
0 0 00000 UNITED STATES None
1 1 01000 ALABAMA None None
2 2 01001 Autauga County, AL
3 3 01003 Baldwin County, AL
4 4 01005 Barbour County, AL
The easiest way to do this in one command is to use which
command and also need not to change the factors into character by doing this:
junk$nm[which(junk$nm=="B")]<-"b"
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
//Suppose you have int and you wan to convert it to Long
int i=78;
//convert to Long
Long l=Long.valueOf(i)
The secret event that keeps angular ngModel synchronous is the event call input. Hence the best answer to your question should be:
<input type="text" [(ngModel)]="mymodel" (input)="valuechange($event)" />
{{mymodel}}
You can print the request type using:
request.getMethod();
You can print all the headers as mentioned here:
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("Header Name - " + headerName + ", Value - " + request.getHeader(headerName));
}
To print all the request params, use this:
Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements()){
String paramName = params.nextElement();
System.out.println("Parameter Name - "+paramName+", Value - "+request.getParameter(paramName));
}
request
is the instance of HttpServletRequest
You can beautify the outputs as you desire.
Now Update word-wrap is replace by :
overflow-wrap:break-word;
Compatible old navigator and css 3 it's good alternative !
it's evolution of word-wrap ( since 2012... )
See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap
See compatibility full : http://caniuse.com/#search=overflow-wrap
Wrap your strings in / /i
. This is an easy way to use regex to ignore casing
I use a handy app called Karabiner to do this, and many other things. It's free and open source.
It's a keyboard remapper, with a lot of handy presets for many common remaps that people may want to do.
As you can see from the screenshot, this remap is included as a preset in Karabiner.
Hope this helps. Happy remapping!
Guys found the perfect way to monitor ALL traffic that is flowing locally between requests from my machine to my machine:
Install Wireshark
When you need to capture traffic that is flowing from a localhost to a localhost then you will struggle to use wireshark as this only monitors incoming traffic on the network card. The way to do this is to add a route to windows that will force all traffic through a gateway and this be captured on the network interface.
To do this, add a route with <ip address>
<gateway>
:
cmd> route add 192.168.20.30 192.168.20.1
Then run a capture on wireshark (make sure you select the interface that has bytes flowing through it) Then filter.
The newly added routes will come up in black. (as they are local addresses)
First of all, do you really need to store indices like this? Have you looked into std::map, enabling you to store key => value pairs?
Secondly, if you used iterators instead, you would be able to return std::vector.end() to indicate an invalid result. To convert an iterator to an index you simply use
size_t i = it - myvector.begin();
Building on @tmullaney 's answer, you can also left join in the sys.objects view to get insight when explicit permissions have been granted on objects. Make sure to use the LEFT join:
SELECT DISTINCT pr.principal_id, pr.name AS [UserName], pr.type_desc AS [User_or_Role], pr.authentication_type_desc AS [Auth_Type], pe.state_desc,
pe.permission_name, pe.class_desc, o.[name] AS 'Object'
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
LEFT JOIN sys.objects AS o on (o.object_id = pe.major_id)