Please check for all the constraints for all the views and review complete storyboard. Usually this happens because of that.
Regards, Arora
You might want to learn vim because you might not be happy with the editors you're already using.
You might want to learn vim because many people say it is cool. Just look how many answers you've got to this question.
I will provide an additional reason for learning vim. It has a reputation for the quality and the completeness of its docs. So you will find most answers to your questions in its help system as soon as you will manage to stick the proper keywords in your help queries.
I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:
For Mobile
@media screen and (max-width:767px) {
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
For Tablet
@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
Desktop
make as per your design requirement enjoy...(:
Thanks, Jitu
After hours of struggling, I solved it by including the following within app/build.gradle:
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
If you installed Python 2.7, I think you could use pip2
and pip2.7
to install packages specifically for Python 2, like
pip2 install some_pacakge
or
pip2.7 install some_package
And you may use pip3
or pip3.5
to install pacakges specifically for Python 3.
how do i append a number into the drug_dictionary?
Do you wish to add "a number" or a set of values?
I use dictionaries to build associative arrays and lookup tables quite a bit.
Since python is so good at handling strings, I often use a string and add the values into a dict as a comma separated string
drug_dictionary = {}
drug_dictionary={'MORPHINE':'',
'OXYCODONE':'',
'OXYMORPHONE':'',
'METHADONE':'',
'BUPRENORPHINE':'',
'HYDROMORPHONE':'',
'CODEINE':'',
'HYDROCODONE':''}
drug_to_update = 'MORPHINE'
try:
oldvalue = drug_dictionary[drug_to_update]
except:
oldvalue = ''
# to increment a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s" % newval
# to append a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval)
The Append method allows for storing a list of values but leaves you will a trailing comma
which you can remove with
drug_dictionary[drug_to_update][:-1]
the result of the appending the values as a string means that you can append lists of values as you need too and
print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update])
can return
'MORPHINE':'10,5,7,42,12,'
This might also work for you
import numpy as np
normalized_v = v / np.sqrt(np.sum(v**2))
but fails when v
has length 0.
In that case, introducing a small constant to prevent the zero division solves this.
I would recommend you using the Conditional Attribute!
Update: 3.5 years later
You can use #if
like this (example copied from MSDN):
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
Only useful for excluding parts of methods.
If you use #if
to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.
If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if
with a method that returns a value you have to hide all pieces of code that call it too.
Here is an example:
// calling Class1.ConditionalMethod() will be ignored at runtime // unless the DEBUG constant is defined using System.Diagnostics; class Class1 { [Conditional("DEBUG")] public static void ConditionalMethod() { Console.WriteLine("Executed Class1.ConditionalMethod"); } }
Summary:
I would use #ifdef
in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though.
You may want to use #if
to avoid dependencies because with Conditional attribute your code is still compiled.
Update - new answer here: https://stackoverflow.com/a/19454282/411229. This answer only applies to those on Spring versions before 3.2.
I've looked for a while for a more definitive solution to this. This blog post seems to cover all my needs and doesn't rely on ordering of bean declarations. All credit to Mattias Severson. http://www.jayway.com/2011/11/30/spring-integration-tests-part-i-creating-mock-objects/
Basically, implement a FactoryBean
package com.jayway.springmock;
import org.mockito.Mockito;
import org.springframework.beans.factory.FactoryBean;
/**
* A {@link FactoryBean} for creating mocked beans based on Mockito so that they
* can be {@link @Autowired} into Spring test configurations.
*
* @author Mattias Severson, Jayway
*
* @see FactoryBean
* @see org.mockito.Mockito
*/
public class MockitoFactoryBean<T> implements FactoryBean<T> {
private Class<T> classToBeMocked;
/**
* Creates a Mockito mock instance of the provided class.
* @param classToBeMocked The class to be mocked.
*/
public MockitoFactoryBean(Class<T> classToBeMocked) {
this.classToBeMocked = classToBeMocked;
}
@Override
public T getObject() throws Exception {
return Mockito.mock(classToBeMocked);
}
@Override
public Class<?> getObjectType() {
return classToBeMocked;
}
@Override
public boolean isSingleton() {
return true;
}
}
Next update your spring config with the following:
<beans...>
<context:component-scan base-package="com.jayway.example"/>
<bean id="someDependencyMock" class="com.jayway.springmock.MockitoFactoryBean">
<constructor-arg name="classToBeMocked" value="com.jayway.example.SomeDependency" />
</bean>
</beans>
Use:
def num(s):
try:
for each in s:
yield int(each)
except ValueError:
yield float(each)
a = num(["123.55","345","44"])
print a.next()
print a.next()
This is the most Pythonic way I could come up with.
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
This worked for me
<script data-main="your-script.js" src="require.js"></script>
Notes!
Use require(['moudle-name'])
in your-script.js
,
not require('moudle-name')
Use const {ipcRenderer} = require(['electron'])
,
not const {ipcRenderer} = require('electron')
.NET 4.5 is not a side-by-side version, it replaces the assemblies for 4.0. Much like .NET 3.0, 3.5 and 3.5SP1 replaced the assemblies for 2.0. And added some new ones. The CLR version is still 4.0.30319. You only care about the reference assemblies, they are in c:\program files\reference assemblies.
BEGIN
FOR r IN (select sid,serial# from v$session where username='user')
LOOP
EXECUTE IMMEDIATE 'alter system kill session ''' || r.sid || ',' || r.serial# || '''';
END LOOP;
END;
/
It works for me.
I'd like to add one suggestion I've used, based on defense in depth. You don't need to have the same auth&auth system for admins as regular users. You can have a separate login form on a separate url executing separate code for requests that will grant high privileges. This one can make choices that would be a total pain to regular users. One such that I've used is to actually scramble the login URL for admin access and email the admin the new URL. Stops any brute force attack right away as your new URL can be arbitrarily difficult (very long random string) but your admin user's only inconvenience is following a link in their email. The attacker no longer knows where to even POST to.
That is my code, dont forget = object: if don't put don't works
val queue = Volley.newRequestQueue(this)
val url = "http://35.237.133.137:8080/lamarrullaWS/rest/lamarrullaAPI"
// Request a string response from the provided URL.
val jsonObjectRequest = object: JsonObjectRequest(Request.Method.GET, url, null,
Response.Listener { response ->
txtPrueba.text = "Response: %s".format(response.toString())
},
Response.ErrorListener { txtPrueba.text = "That didn't work!" }
)
{
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
headers.put("Content-Type", "application/json")
return headers
}
}
queue.add(jsonObjectRequest)
It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.
Try unmounting the overflow partition:
umount /tmp
or
umount overflow
You don't need to copy things around, webpack works different than gulp. Webpack is a module bundler and everything you reference in your files will be included. You just need to specify a loader for that.
So if you write:
var myImage = require("./static/myImage.jpg");
Webpack will first try to parse the referenced file as JavaScript (because that's the default). Of course, that will fail. That's why you need to specify a loader for that file type. The file- or url-loader for instance take the referenced file, put it into webpack's output folder (which should be build
in your case) and return the hashed url for that file.
var myImage = require("./static/myImage.jpg");
console.log(myImage); // '/build/12as7f9asfasgasg.jpg'
Usually loaders are applied via the webpack config:
// webpack.config.js
module.exports = {
...
module: {
loaders: [
{ test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3)$/, loader: "file" }
]
}
};
Of course you need to install the file-loader first to make this work.
Use:
YourActivityName.this
Instead of:
getApplicationContext();
I made use of sendkeys in shell scripting using a vbsscript file. Below is the code in vbs file,
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.SendKeys "C:\Demo.txt"
WshShell.SendKeys "{ENTER}"
Below is the selenium code line to run this vbs file,
driver.findElement(By.id("uploadname1")).click();
Thread.sleep(1000);
Runtime.getRuntime().exec( "wscript C:/script.vbs" );
Just give full path to exclusion file: eg..
-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt
In this example the file would be located " C:\list-of-excluded-files.txt "
or...
correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt
In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "
Full path fixes syntax error.
Here is a cool feature I discovered recently, I tried this on the console and it seems to work:
var text = "border-bottom-left-radius";
var newText = text.replace(/-/g,function(match, index){
return " " + index + " ";
});
Which returned: "border 6 bottom 13 left 18 radius"
So this seems to be what you are looking for.
I had a similar problem, and ended up applying Kalman's excellent answer with the code below (not quite as neat, but arguably more expansible):
namespace MvcHtmlHelpers
{
//http://stackoverflow.com/questions/5110028/add-css-or-js-files-to-layout-head-from-views-or-partial-views#5148224
public static partial class HtmlExtensions
{
public static AssetsHelper Assets(this HtmlHelper htmlHelper)
{
return AssetsHelper.GetInstance(htmlHelper);
}
}
public enum BrowserType { Ie6=1,Ie7=2,Ie8=4,IeLegacy=7,W3cCompliant=8,All=15}
public class AssetsHelper
{
public static AssetsHelper GetInstance(HtmlHelper htmlHelper)
{
var instanceKey = "AssetsHelperInstance";
var context = htmlHelper.ViewContext.HttpContext;
if (context == null) {return null;}
var assetsHelper = (AssetsHelper)context.Items[instanceKey];
if (assetsHelper == null){context.Items.Add(instanceKey, assetsHelper = new AssetsHelper(htmlHelper));}
return assetsHelper;
}
private readonly List<string> _styleRefs = new List<string>();
public AssetsHelper AddStyle(string stylesheet)
{
_styleRefs.Add(stylesheet);
return this;
}
private readonly List<string> _scriptRefs = new List<string>();
public AssetsHelper AddScript(string scriptfile)
{
_scriptRefs.Add(scriptfile);
return this;
}
public IHtmlString RenderStyles()
{
ItemRegistrar styles = new ItemRegistrar(ItemRegistrarFormatters.StyleFormat,_urlHelper);
styles.Add(Libraries.UsedStyles());
styles.Add(_styleRefs);
return styles.Render();
}
public IHtmlString RenderScripts()
{
ItemRegistrar scripts = new ItemRegistrar(ItemRegistrarFormatters.ScriptFormat, _urlHelper);
scripts.Add(Libraries.UsedScripts());
scripts.Add(_scriptRefs);
return scripts.Render();
}
public LibraryRegistrar Libraries { get; private set; }
private UrlHelper _urlHelper;
public AssetsHelper(HtmlHelper htmlHelper)
{
_urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
Libraries = new LibraryRegistrar();
}
}
public class LibraryRegistrar
{
public class Component
{
internal class HtmlReference
{
internal string Url { get; set; }
internal BrowserType ServeTo { get; set; }
}
internal List<HtmlReference> Styles { get; private set; }
internal List<HtmlReference> Scripts { get; private set; }
internal List<string> RequiredLibraries { get; private set; }
public Component()
{
Styles = new List<HtmlReference>();
Scripts = new List<HtmlReference>();
RequiredLibraries = new List<string>();
}
public Component Requires(params string[] libraryNames)
{
foreach (var lib in libraryNames)
{
if (!RequiredLibraries.Contains(lib))
{ RequiredLibraries.Add(lib); }
}
return this;
}
public Component AddStyle(string url, BrowserType serveTo = BrowserType.All)
{
Styles.Add(new HtmlReference { Url = url, ServeTo=serveTo });
return this;
}
public Component AddScript(string url, BrowserType serveTo = BrowserType.All)
{
Scripts.Add(new HtmlReference { Url = url, ServeTo = serveTo });
return this;
}
}
private readonly Dictionary<string, Component> _allLibraries = new Dictionary<string, Component>();
private List<string> _usedLibraries = new List<string>();
internal IEnumerable<string> UsedScripts()
{
SetOrder();
var returnVal = new List<string>();
foreach (var key in _usedLibraries)
{
returnVal.AddRange(from s in _allLibraries[key].Scripts
where IncludesCurrentBrowser(s.ServeTo)
select s.Url);
}
return returnVal;
}
internal IEnumerable<string> UsedStyles()
{
SetOrder();
var returnVal = new List<string>();
foreach (var key in _usedLibraries)
{
returnVal.AddRange(from s in _allLibraries[key].Styles
where IncludesCurrentBrowser(s.ServeTo)
select s.Url);
}
return returnVal;
}
public void Uses(params string[] libraryNames)
{
foreach (var name in libraryNames)
{
if (!_usedLibraries.Contains(name)){_usedLibraries.Add(name);}
}
}
public bool IsUsing(string libraryName)
{
SetOrder();
return _usedLibraries.Contains(libraryName);
}
private List<string> WalkLibraryTree(List<string> libraryNames)
{
var returnList = new List<string>(libraryNames);
int counter = 0;
foreach (string libraryName in libraryNames)
{
WalkLibraryTree(libraryName, ref returnList, ref counter);
}
return returnList;
}
private void WalkLibraryTree(string libraryName, ref List<string> libBuild, ref int counter)
{
if (counter++ > 1000) { throw new System.Exception("Dependancy library appears to be in infinate loop - please check for circular reference"); }
Component library;
if (!_allLibraries.TryGetValue(libraryName, out library))
{ throw new KeyNotFoundException("Cannot find a definition for the required style/script library named: " + libraryName); }
foreach (var childLibraryName in library.RequiredLibraries)
{
int childIndex = libBuild.IndexOf(childLibraryName);
if (childIndex!=-1)
{
//child already exists, so move parent to position before child if it isn't before already
int parentIndex = libBuild.LastIndexOf(libraryName);
if (parentIndex>childIndex)
{
libBuild.RemoveAt(parentIndex);
libBuild.Insert(childIndex, libraryName);
}
}
else
{
libBuild.Add(childLibraryName);
WalkLibraryTree(childLibraryName, ref libBuild, ref counter);
}
}
return;
}
private bool _dependenciesExpanded;
private void SetOrder()
{
if (_dependenciesExpanded){return;}
_usedLibraries = WalkLibraryTree(_usedLibraries);
_usedLibraries.Reverse();
_dependenciesExpanded = true;
}
public Component this[string index]
{
get
{
if (_allLibraries.ContainsKey(index))
{ return _allLibraries[index]; }
var newComponent = new Component();
_allLibraries.Add(index, newComponent);
return newComponent;
}
}
private BrowserType _requestingBrowser;
private BrowserType RequestingBrowser
{
get
{
if (_requestingBrowser == 0)
{
var browser = HttpContext.Current.Request.Browser.Type;
if (browser.Length > 2 && browser.Substring(0, 2) == "IE")
{
switch (browser[2])
{
case '6':
_requestingBrowser = BrowserType.Ie6;
break;
case '7':
_requestingBrowser = BrowserType.Ie7;
break;
case '8':
_requestingBrowser = BrowserType.Ie8;
break;
default:
_requestingBrowser = BrowserType.W3cCompliant;
break;
}
}
else
{
_requestingBrowser = BrowserType.W3cCompliant;
}
}
return _requestingBrowser;
}
}
private bool IncludesCurrentBrowser(BrowserType browserType)
{
if (browserType == BrowserType.All) { return true; }
return (browserType & RequestingBrowser) != 0;
}
}
public class ItemRegistrar
{
private readonly string _format;
private readonly List<string> _items;
private readonly UrlHelper _urlHelper;
public ItemRegistrar(string format, UrlHelper urlHelper)
{
_format = format;
_items = new List<string>();
_urlHelper = urlHelper;
}
internal void Add(IEnumerable<string> urls)
{
foreach (string url in urls)
{
Add(url);
}
}
public ItemRegistrar Add(string url)
{
url = _urlHelper.Content(url);
if (!_items.Contains(url))
{ _items.Add( url); }
return this;
}
public IHtmlString Render()
{
var sb = new StringBuilder();
foreach (var item in _items)
{
var fmt = string.Format(_format, item);
sb.AppendLine(fmt);
}
return new HtmlString(sb.ToString());
}
}
public class ItemRegistrarFormatters
{
public const string StyleFormat = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
public const string ScriptFormat = "<script src=\"{0}\" type=\"text/javascript\"></script>";
}
}
The project contains a static AssignAllResources method:
assets.Libraries["jQuery"]
.AddScript("~/Scripts/jquery-1.10.0.min.js", BrowserType.IeLegacy)
.AddScript("~/Scripts//jquery-2.0.1.min.js",BrowserType.W3cCompliant);
/* NOT HOSTED YET - CHECK SOON
.AddScript("//ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js",BrowserType.W3cCompliant);
*/
assets.Libraries["jQueryUI"].Requires("jQuery")
.AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js",BrowserType.Ie6)
.AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/eggplant/jquery-ui.css",BrowserType.Ie6)
.AddScript("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js", ~BrowserType.Ie6)
.AddStyle("//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/eggplant/jquery-ui.css", ~BrowserType.Ie6);
assets.Libraries["TimePicker"].Requires("jQueryUI")
.AddScript("~/Scripts/jquery-ui-sliderAccess.min.js")
.AddScript("~/Scripts/jquery-ui-timepicker-addon-1.3.min.js")
.AddStyle("~/Content/jQueryUI/jquery-ui-timepicker-addon.css");
assets.Libraries["Validation"].Requires("jQuery")
.AddScript("//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js")
.AddScript("~/Scripts/jquery.validate.unobtrusive.min.js")
.AddScript("~/Scripts/mvcfoolproof.unobtrusive.min.js")
.AddScript("~/Scripts/CustomClientValidation-1.0.0.min.js");
assets.Libraries["MyUtilityScripts"].Requires("jQuery")
.AddScript("~/Scripts/GeneralOnLoad-1.0.0.min.js");
assets.Libraries["FormTools"].Requires("Validation", "MyUtilityScripts");
assets.Libraries["AjaxFormTools"].Requires("FormTools", "jQueryUI")
.AddScript("~/Scripts/jquery.unobtrusive-ajax.min.js");
assets.Libraries["DataTables"].Requires("MyUtilityScripts")
.AddScript("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js")
.AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css")
.AddStyle("//ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables_themeroller.css");
assets.Libraries["MvcDataTables"].Requires("DataTables", "jQueryUI")
.AddScript("~/Scripts/jquery.dataTables.columnFilter.min.js");
assets.Libraries["DummyData"].Requires("MyUtilityScripts")
.AddScript("~/Scripts/DummyData.js")
.AddStyle("~/Content/DummyData.css");
in the _layout page
@{
var assets = Html.Assets();
CurrentResources.AssignAllResources(assets);
Html.Assets().RenderStyles()
}
</head>
...
@Html.Assets().RenderScripts()
</body>
and in the partial(s) and views
Html.Assets().Libraries.Uses("DataTables");
Html.Assets().AddScript("~/Scripts/emailGridUtilities.js");
SHIFT+Page Up and SHIFT+Page Down. If it doesn't work try this and then it should:
Go the terminal program, and make sure
Edit/Profile Preferences/Scrolling/Scrollback/Unlimited
is checked.
The exact location of this option might be somewhere different though, I see that you are using Redhat.
You'll have to jailbreak your device.
The main difference between return false
and event.preventDefault()
is that your code below return false
will not be executed and in event.preventDefault()
case your code will execute after this statement.
When you write return false it do the following things for you behind the scenes.
* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();
Just use xcopy /y source destination
def count_letter(string):
count = 0
for i in range(len(string)):
if string[i].isalpha():
count += 1
return count
print(count_letter('The grey old fox is an idiot.'))
How about, this. Not mentioned here yet.
py 2 & 3
a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2
After some time with Google I asked on the ask ubuntu chat room.
A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:
grep -P "(^|\s)abc(\s|$)"
gives the result I was looking for. -P is an experimental implementation of perl regexps.
grepping for abc
and then using filters like grep -v '@abc'
(this is far from perfect...) should also work, but my patch does something similar.
Get the current task's user_struct
#define get_current_user() \
({ \
struct user_struct *__u; \
const struct cred *__cred; \
__cred = current_cred(); \
__u = get_uid(__cred->user); \
__u; \
})
You can also use AutoHotKey with a simple script to open a Jupyter Notebook server in a default directory (CTRL+I) or a path highlighted in explorer (or elsewhere with CTRL+SHIFT+I).
#SingleInstance Force
#NoTrayIcon
SetTitleMatchMode RegEx
; Press CTRL+ALT+I in a Windows Explorer window to launch a IPython notebook server in the current folder.
^+!i::
; Get the current path.
Send ^l
; Backup the current clipboard.
ClipSaved := ClipboardAll
; Copy and save the current path.
Send ^c
ClipWait
x = %Clipboard%
; Restore the clipboard.
Clipboard := ClipSaved
ClipSaved = ; Free the memory in case the clipboard was very large.
; Now, run the IPython notebook server.
RunWait, ipython notebook --notebook-dir "%x%", , min
return
^i::
; Now, run the IPython notebook server.
RunWait, jupyter notebook --notebook-dir "C:\Path\To\Workspace", , min
return
; Press CTRL+ALT+P to kill all Python processes.
^!p::
Run, taskkill /f /im python.exe, , min
return
Both methods ensure that your process doesn't end before all of your threads have ended.
The join method has your thread of the main
function explicitly wait for all threads that are to be "joined".
The pthread_exit
method terminates your main
function and thread in a controlled way. main
has the particularity that ending main
otherwise would be terminating your whole process including all other threads.
For this to work, you have to be sure that none of your threads is using local variables that are declared inside them main
function. The advantage of that method is that your main
doesn't have to know all threads that have been started in your process, e.g because other threads have themselves created new threads that main
doesn't know anything about.
Here is a simpler option that works when I encounter this.
After you create the connection, select the connection and open the Properties. In the Expressions category find Password. Re-enter the password and hit Enter. It will now be saved to the connection.
import java.net.DatagramSocket;
import java.net.InetAddress;
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
ip = socket.getLocalAddress().getHostAddress();
}
This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8
is not needed to be reachable.
Connect
on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.
So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.
Edit:
As @macomgil says, for MacOS you can do this:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
To get the current time in the local timezone as a naive datetime object:
from datetime import datetime
naive_dt = datetime.now()
If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).
To get the current time in UTC as a naive datetime object:
naive_utc_dt = datetime.utcnow()
To get the current time as an aware datetime object in Python 3.3+:
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
To get the current time in the given time zone from the tz database:
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.
Another suggestion is to do that way:
string = "abcd\n"
print(string.replace("\n","\\n"))
But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n
No; instances of class File
represent a path in a filesystem. Therefore, you can use that function only with a file. But perhaps there is an overload that takes an InputStream
instead?
To link to a form you need:
Form2 form2 = new Form2();
form2.show();
this.hide();
then hide the previous form
Or using the famous Joda Time library:
DateTime dateTime = new DateTime();
dateTime = dateTime.minusHours(1);
Date modifiedDate = dateTime.toDate();
Check out the Zend_Db_Profiler. This allows you to log any SQL statement as it is prepared and executed. It works for UPDATE statements as well as SELECT queries.
Assuming you want curl installed: just execute the install command and see what happens.
$ sudo yum install curl
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirrors.cat.pdx.edu
* epel: mirrors.kernel.org
* extras: mirrors.cat.pdx.edu
* remi-php72: repo1.sea.innoscale.net
* remi-safe: repo1.sea.innoscale.net
* updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do
For the IBM JVM, the command is the following:
java -verbose:sizes -version
For more information about the IBM SDK for Java 8: http://www-01.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.lnx.80.doc/diag/appendixes/defaults.html?lang=en
[Late to the party...]
Another way to do this without the overhead of an Ajax call or WebService handler is to load a special ASPX page after a given amount of time (i.e., prior to the session state time-out, which is typically 20 minutes):
// Client-side JavaScript
function pingServer() {
// Force the loading of a keep-alive ASPX page
var img = new Image(1, 1);
img.src = '/KeepAlive.aspx';
}
The KeepAlive.aspx
page is simply an empty page which does nothing but touch/refresh the Session
state:
// KeepAlive.aspx.cs
public partial class KeepSessionAlive: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Refresh the current user session
Session["refreshTime"] = DateTime.UtcNow;
}
}
This works by creating an img
(image) element and forcing the browser to load its contents from the KeepAlive.aspx
page. Loading that page causes the server to touch (update) the Session
object, extending the session's expiration sliding time window (typically by another 20 minutes). The actual web page contents are discarded by the browser.
An alternative, and perhaps cleaner, way to do this is to create a new iframe
element and load the KeepAlive.aspx
page into it. The iframe
element is hidden, such as by making it a child element of a hidden div
element somewhere on the page.
Activity on the page itself can be detected by intercepting mouse and keyboard actions for the entire page body:
// Called when activity is detected
function activityDetected(evt) {
...
}
// Watch for mouse or keyboard activity
function watchForActivity() {
var opts = { passive: true };
document.body.addEventListener('mousemove', activityDetected, opts);
document.body.addEventListener('keydown', activityDetected, opts);
}
I cannot take credit for this idea; see: https://www.codeproject.com/Articles/227382/Alert-Session-Time-out-in-ASP-Net.
use value
instead of query
(must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):
select
xt.Id
, x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
XmlTest xt
cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)
As of verison 2.10, Genymotion can be installed using the toolbar in your emulator. Simply look for the Open GAPPS button.
From what I understand using,
::-webkit-input-placeholder::before
or ::-webkit-input-placeholder::after
,
to add more placeholder content doesn't work anymore. Think its a new Chrome update.
Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:
<input type="text" value="" id="email1" placeholder="I am on one line. I am on a second line etc etc..." />
timeObject.setSeconds(timeObject.getSeconds() + 10)
I made a poster on the wall which moves left and right with intervals. For me it works:
.div-animation {
-webkit-animation: bounce 2000ms ease-out;
-moz-animation: bounce 2000ms ease-out;
-o-animation: bounce 2000ms ease-out;
animation: bounce 2000ms ease-out infinite;
-webkit-animation-delay: 2s; /* Chrome, Safari, Opera */
animation-delay: 2s;
transform-origin: 55% 10%;
}
@-webkit-keyframes bounce {
0% {
transform: rotate(0deg);
}
3% {
transform: rotate(1deg);
}
6% {
transform: rotate(2deg);
}
9% {
transform: rotate(3deg);
}
12% {
transform: rotate(2deg);
}
15% {
transform: rotate(1deg);
}
18% {
transform: rotate(0deg);
}
21% {
transform: rotate(-1deg);
}
24% {
transform: rotate(-2deg);
}
27% {
transform: rotate(-3deg);
}
30% {
transform: rotate(-2deg);
}
33% {
transform: rotate(-1deg);
}
36% {
transform: rotate(0deg);
}
100% {
transform: rotate(0deg);
}
}
I had the same challenge. This is the solution I found to add users to roles.
internal class Security
{
ApplicationDbContext context = new ApplicationDbContext();
internal void AddUserToRole(string userName, string roleName)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
try
{
var user = UserManager.FindByName(userName);
UserManager.AddToRole(user.Id, roleName);
context.SaveChanges();
}
catch
{
throw;
}
}
}
Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.
If you had generate a SSH-key with passphrase and then you forget your passphrase for this SSH-key,there's no way to recover it, You'll need to generate a brand new SSH keypair or switch to HTTPS cloning so you can use your GitHub password instead.
If you configured your SSH passphrase with the OS X Keychain, you may be able to recover it.
Refer to Github help - How do I recover my SSH key passphrase?
From this docs
I understood that you should use:
Try using the context-application instead of a context-activity
Forgot to relate to the first code snippet. I wouldn't use forEach
at all. Since you are collecting the elements of the Stream
into a List
, it would make more sense to end the Stream
processing with collect
. Then you would need peek
in order to set the ID.
List<Entry> updatedEntries =
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());
For the second snippet, forEach
can execute multiple expressions, just like any lambda expression can :
entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});
However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null
) if you do.
<div class="outer">
<div class="target">
<div class="filler">
</div>
</div>
</div>
.outer{
width:100%;
height: 100px;
}
.target{
position: absolute;
width: auto;
height: 100px;
left: 50%;
transform: translateX(-50%);
}
.filler{
position:relative;
width:150px;
height:20px;
}
If the target element is absolutely positioned, you can center it by moving it 50% in one direction (left: 50%
) and then transforming it 50% in the opposition direction (transform:translateX(-50%)
). This works without defining the target element's width (or with width:auto
). The parent element's position can be static, absolute, relative, or fixed.
Peters' python 2 workaround fails on an edge case:
d = {u'keyword': u'bad credit \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False).decode('utf8')
try:
json_file.write(data)
except TypeError:
# Decode data to Unicode first
json_file.write(data.decode('utf8'))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)
It was crashing on the .decode('utf8') part of line 3. I fixed the problem by making the program much simpler by avoiding that step as well as the special casing of ascii:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False, encoding='utf8')
json_file.write(unicode(data))
cat filename
{"keyword": "bad credit çredit cards"}
It is very simple.
press f2 key to rename project .
and import multiple copy of android projects with the same package .
Similar to another answer here, but change the http in the rewrite to to $scheme like so:
server {
listen 80;
server_name test.com;
rewrite ^ $scheme://www.test.com$request_uri? permanent;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
I had to do this to redirect www.test.com to test.com.
Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.
df2<-df1[complete.cases(df1),]
model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)
resid2 <- residuals(model2,type="deviance")
model2_1 <- update(model2,.~.+ Lag(resid2,1), na.action=na.omit)
I answer this coming from a component-based architecture, where an organisation may be running many components that may rely on each other. During a propagating failure, logging levels should help to identify both which components are affected and which are a root cause.
ERROR - This component has had a failure and the cause is believed to be internal (any internal, unhandled exception, failure of encapsulated dependency... e.g. database, REST example would be it has received a 4xx error from a dependency). Get me (maintainer of this component) out of bed.
WARN - This component has had a failure believed to be caused by a dependent component (REST example would be a 5xx status from a dependency). Get the maintainers of THAT component out of bed.
INFO - Anything else that we want to get to an operator. If you decide to log happy paths then I recommend limiting to 1 log message per significant operation (e.g. per incoming http request).
For all log messages be sure to log useful context (and prioritise on making messages human readable/useful rather than having reams of "error codes")
A nice way to visualise the above logging levels is to imagine a set of monitoring screens for each component. When all running well they are green, if a component logs a WARNING then it will go orange (amber) if anything logs an ERROR then it will go red.
In the event of an incident you should have one (root cause) component go red and all the affected components should go orange/amber.
put this line in yor file .gradle above the Java conf.
apply plugin: 'java'
compileJava {options.encoding = "UTF-8"}
Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.
I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).
var x = parseInt(455/10);
The parseInt() function parses a string and returns an integer.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal)
I use win7 and has same problem. Today I solved this problem, through loading with many error with my project just give order to continue after that goto Project=> Component => Microsoft Windows Common Controls 6.0 (SP6) then save the project (file use was c:\windows\syswow64\mscomctl.ocx)
for python2 use:
py -2 -m pip install beautifulsoup4
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
Great helps above, but if you having the similar environment like I did, this is how I get it to work.
Edit this file /etc/profile.d/apache-maven.sh, such as the following, note that it will affect the whole system.
$ cat /etc/profile.d/apache-maven.sh
MAVEN_HOME=/usr/share/apache-maven
M2_HOME=$MAVEN_HOME
PATH=$MAVEN_HOME/bin:$PATH
# change below to the jdk you want mvn to reference.
JAVA_HOME=/usr/java/jdk1.7.0_40/
export MAVEN_HOME
export M2_HOME
export PATH
export JAVA_HOME
The algorithm is documented in RFC6238. Goes a bit like this:
I've had a play implementing the algorithm in javascript here: http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/
There's also one important tricky treat of ".PHONY" - when a physical target depends on phony target that depends on another physical target:
TARGET1 -> PHONY_FORWARDER1 -> PHONY_FORWARDER2 -> TARGET2
You'd simply expect that if you updated TARGET2, then TARGET1 should be considered stale against TARGET1, so TARGET1 should be rebuild. And it really works this way.
The tricky part is when TARGET2 isn't stale against TARGET1 - in which case you should expect that TARGET1 shouldn't be rebuild.
This surprisingly doesn't work because: the phony target was run anyway (as phony targets normally do), which means that the phony target was considered updated. And because of that TARGET1 is considered stale against the phony target.
Consider:
all: fileall
fileall: file2 filefwd
echo file2 file1 >fileall
file2: file2.src
echo file2.src >file2
file1: file1.src
echo file1.src >file1
echo file1.src >>file1
.PHONY: filefwd
.PHONY: filefwd2
filefwd: filefwd2
filefwd2: file1
@echo "Produced target file1"
prepare:
echo "Some text 1" >> file1.src
echo "Some text 2" >> file2.src
You can play around with this:
You can see that fileall depends on file1 indirectly through a phony target - but it always gets rebuilt due to this dependency. If you change the dependency in fileall
from filefwd
to file
, now fileall
does not get rebuilt every time, but only when any of dependent targets is stale against it as a file.
This is for people who uses mruby
and do not have any symbolize_keys
method defined:
class Hash
def symbolize_keys!
self.keys.each do |k|
if self[k].is_a? Hash
self[k].symbolize_keys!
end
if k.is_a? String
raise RuntimeError, "Symbolizing key '#{k}' means overwrite some data (key :#{k} exists)" if self[k.to_sym]
self[k.to_sym] = self[k]
self.delete(k)
end
end
return self
end
end
The method:
String
RuntimeError
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick
method if you select the previous value selected in the drop down..
By the way, the shortcut to pushing the current branch to a remote with the same name:
$ git push -u origin HEAD
Use position:fixed
on the video, set it to 100% width/height, and put a negative z-index
on it so it appears behind everything.
If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.
HTML
<video id="video_background" src="video.mp4" autoplay>
(Add webm and ogg sources to support more browsers)
CSS
#video_background {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: -1000;
}
It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.
Here we have two possible cases given below
from __future__ import division
print(4/100)
print(4//100)
As a supplement to the question and above answers there is also an important difference between plt.subplots()
and plt.subplot()
, notice the missing 's'
at the end.
One can use plt.subplots()
to make all their subplots at once and it returns the figure and axes (plural of axis) of the subplots as a tuple. A figure can be understood as a canvas where you paint your sketch.
# create a subplot with 2 rows and 1 columns
fig, ax = plt.subplots(2,1)
Whereas, you can use plt.subplot()
if you want to add the subplots separately. It returns only the axis of one subplot.
fig = plt.figure() # create the canvas for plotting
ax1 = plt.subplot(2,1,1)
# (2,1,1) indicates total number of rows, columns, and figure number respectively
ax2 = plt.subplot(2,1,2)
However, plt.subplots()
is preferred because it gives you easier options to directly customize your whole figure
# for example, sharing x-axis, y-axis for all subplots can be specified at once
fig, ax = plt.subplots(2,2, sharex=True, sharey=True)
whereas, with plt.subplot()
, one will have to specify individually for each axis which can become cumbersome.
I can easily handle this type of task using bootbox.js library. At first you need to include bootbox JS file. Then in your event handler function simply write following code:
bootbox.confirm("Are you sure to want to delete , function(result) {
//here result will be true
// delete process code goes here
});
Offical bootboxjs site
There is also th:classappend
.
<a href="" class="baseclass" th:classappend="${isAdmin} ? adminclass : userclass"></a>
If isAdmin
is true
, then this will result in:
<a href="" class="baseclass adminclass"></a>
var myInt = int.parse('12345');
assert(myInt is int);
print(myInt); // 12345
print(myInt.runtimeType);
var myDouble = double.parse('123.45');
assert(myInt is double);
print(myDouble); // 123.45
print(myDouble.runtimeType);
The key here is to get the first day of the month. For that, there are several options. In terms of performance, our tests show that there isn't a significant difference between them - we wrote a whole blog article on the topic. Our findings show that what really matters is whether you need the result to be VARCHAR, DATETIME, or DATE.
The fastest solution to the real problem of getting the first day of the month returns VARCHAR:
SELECT CONCAT(LEFT(CURRENT_DATE, 7), '-01') AS first_day_of_month;
The second fastest solution gives a DATETIME result - this runs about 3x slower than the previous:
SELECT TIMESTAMP(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AS first_day_of_month;
The slowest solutions return DATE objects. Don't believe me? Run this SQL Fiddle and see for yourself
In your case, since you need to compare the value with other DATE values in your table, it doesn't really matter what methodology you use because MySQL will do the conversion implicitly even if your formula doesn't return a DATE object.
So really, take your pick. Which is most readable for you? I'd pick the first since it's the shortest and arguably the simplest:
SELECT * FROM table_name
WHERE date BETWEEN CONCAT(LEFT(CURRENT_DATE, 7), '-01') AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE(CONCAT(LEFT(CURRENT_DATE, 7), '-01')) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (LAST_DAY(CURRENT_DATE) + INTERVAL 1 DAY - INTERVAL 1 MONTH) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE) - 1) DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN (DATE(CURRENT_DATE) - INTERVAL (DAYOFMONTH(CURRENT_DATE)) DAY + INTERVAL 1 DAY) AND CURDATE;
SELECT * FROM table_name
WHERE date BETWEEN DATE_FORMAT(CURRENT_DATE,'%Y-%m-01') AND CURDATE;
By making AutoCompleteType="Disabled",
<asp:TextBox runat="server" ID="txt_userid" AutoCompleteType="Disabled"></asp:TextBox>
By setting autocomplete="off",
<asp:TextBox runat="server" ID="txt_userid" autocomplete="off"></asp:TextBox>
By Setting Form autocomplete="off",
<form id="form1" runat="server" autocomplete="off">
//your content
</form>
By using code in .cs page,
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txt_userid.Attributes.Add("autocomplete", "off");
}
}
By Using Jquery
<head runat = "server" >
< title > < /title> < script src = "Scripts/jquery-1.6.4.min.js" > < /script> < script type = "text/javascript" >
$(document).ready(function()
{
$('#txt_userid').attr('autocomplete', 'off');
});
//document.getElementById("txt_userid").autocomplete = "off"
< /script>
and here is my textbox in ,
<asp:TextBox runat="server" ID="txt_userid" ></asp:TextBox>
By Setting textbox attribute in code,
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
txt_userid.Attributes.Add("autocomplete", "off");
}
}
Other way is using concat() function:
import pandas as pd
In [603]: df = pd.DataFrame({'col1':list("abc"),'col2':range(3)},index = range(3))
In [604]: df
Out[604]:
col1 col2
0 a 0
1 b 1
2 c 2
In [605]: pd.concat([df]*3, ignore_index=True) # Ignores the index
Out[605]:
col1 col2
0 a 0
1 b 1
2 c 2
3 a 0
4 b 1
5 c 2
6 a 0
7 b 1
8 c 2
In [606]: pd.concat([df]*3)
Out[606]:
col1 col2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
0 a 0
1 b 1
2 c 2
Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.
import java.io.ByteArrayOutputStream
private fun encodeImage(bm: Bitmap): String? {
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
The only illegal characters are &
, <
and >
(as well as "
or '
in attributes, depending on which character is used to delimit the attribute value: attr="must use " here, ' is allowed"
and attr='must use ' here, " is allowed'
).
They're escaped using XML entities, in this case you want &
for &
.
Really, though, you should use a tool or library that writes XML for you and abstracts this kind of thing away for you so you don't have to worry about it.
Use PHP Document Object Model:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
$DOM = new DOMDocument;
$DOM->loadHTML($str);
//get all H1
$items = $DOM->getElementsByTagName('h1');
//display all H1 text
for ($i = 0; $i < $items->length; $i++)
echo $items->item($i)->nodeValue . "<br/>";
?>
This outputs as:
T1
T2
T3
[EDIT]: After OP Clarification:
If you want the content like Lorem ipsum. etc, you can directly use this regex:
<?php
$str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>
this outputs:
Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG
Yes, you must open php.ini
and remove the semicolon to:
;extension=php_openssl.dll
If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext
) and add this to php.ini
in the "Dynamic Extensions" section:
extension=php_openssl.dll
Things have changed for PHP > 7. This is what i had to do for PHP 7.2.
Step: 1: Uncomment extension=openssl
Step: 2: Uncomment extension_dir = "ext"
Step: 3: Restart xampp.
Done.
Explanation: ( From php.ini )
If you wish to have an extension loaded automatically, use the following syntax:
extension=modulename
Note : The syntax used in previous PHP versions (extension=<ext>.so
and extension='php_<ext>.dll
) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>
) syntax.
Special Note: Be sure to appropriately set the extension_dir
directive.
The key thing to understand in Java is that Strings are immutable -- you can't change them. So it makes no sense to speak of 'removing a character from a string'. Instead, you make a NEW string with just the characters you want. The other posts in this question give you a variety of ways of doing that, but its important to understand that these don't change the original string in any way. Any references you have to the old string will continue to refer to the old string (unless you change them to refer to a different string) and will not be affected by the newly created string.
This has a number of implications for performance. Each time you are 'modifying' a string, you are actually creating a new string with all the overhead implied (memory allocation and garbage collection). So if you want to make a series of modifications to a string and care only about the final result (the intermediate strings will be dead as soon as you 'modify' them), it may make more sense to use a StringBuilder or StringBuffer instead.
Add the following code within the constructor like so:
public Calculator() {
initComponents();
//the code to be added this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage()); }
Change "color.png" to the file name of the picture you want to insert. Drag and drop this picture onto the package (under Source Packages) of your project.
Run your project.
Don't worry about you should just change .dll from x64 to x86, in the native library.
for example:- you might have selected this (C:\opencv\build\java\x64).
instead you select this for native library(C:\opencv\build\java\x86).
Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.
You can use also this without creating additional variables nor copying the data in the memory like foreach() does.
while (false !== (list($item, $values) = each($array)))
{
...
}
They aren't comparable.
Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.
jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.
The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.
Here is an example of this enhanced for loop from Java Tutorials
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
Output is as follows:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Hope this helps !
Simplified example (with counter):
With Me.lstbox
.ColumnCount = 2
.ColumnWidths = "60;60"
.AddItem
.List(i, 0) = Company_ID
.List(i, 1) = Company_name
i = i + 1
end with
Make sure to start the counter with 0, not 1 to fill up a listbox.
Git submodules are a little bit strange - they're always in "detached head" mode - they don't update to the latest commit on a branch like you might expect.
This does make some sense when you think about it, though. Let's say I create repository foo with submodule bar. I push my changes and tell you to check out commit a7402be from repository foo.
Then imagine that someone commits a change to repository bar before you can make your clone.
When you check out commit a7402be from repository foo, you expect to get the same code I pushed. That's why submodules don't update until you tell them to explicitly and then make a new commit.
Personally I think submodules are the most confusing part of Git. There are lots of places that can explain submodules better than I can. I recommend Pro Git by Scott Chacon.
DELETE a FROM WorkRecord2 a
INNER JOIN Employee b
ON a.EmployeeRun = b.EmployeeNo
Where a.Company = '1'
AND a.Date = '2013-05-06'
I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):
mention permissions in Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
e.g.
File file=new File(path);
long=file.length();//in Bytes
I dont have a copy of Delphi to hand, but I'm fairly certain if you set the wordwrap property to true and the autosize property to false it should wrap any text you put it at the size you make the label. If you want to line break in a certain place then it might work if you set the above settings and paste from a text editor.
Hope this helps.
Use this extension, it generates xpaths based on id or class, which is probably what you want to use.
Click on the browser icon, the panel is shown on the right corner of the page, then click start inspect, then click on any element to get your xpath.
var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"
The proposed regex /\//g
did not work for me; the rest of the line (//g, replacement);
) was commented out.
find -execdir rename
This renames files and directories with a regular expression affecting only basenames.
So for a prefix you could do:
PATH=/usr/bin find . -depth -execdir rename 's/^/Unix_/' '{}' \;
or to affect files only:
PATH=/usr/bin find . -type f -execdir rename 's/^/Unix_/' '{}' \;
-execdir
first cd
s into the directory before executing only on the basename.
I have explained it in more detail at: Find multiple files and rename them in Linux
Try this instead
$(document).ready(function() {
$("#divDialog").dialog(opt).dialog("open");
});
You can also do:
var theDialog = $("#divDialog").dialog(opt);
theDialog.dialog("open");
That's because the dialog is not stored in $('#divDialog')
, but on a new div that is created on the fly and returned by the .dialog(opt)
function.
This is an answer for those not familiar with Vim and coming from other text editors (in my case Sublime Text).
I read through all these answers and it still wasn't clear. If you read through them enough things begin to make sense, but it took me hours of going back and forth between questions.
The first thing is, as others have explained:
Tab Pages, sound a lot like tabs, they act like tabs and look a lot like tabs in most other GUI editors, but they're not. I think it's an a bad mental model that was built on in Vim, which unfortunately clouds the extra power that you have within a tab page.
The first description that I understood was from @crenate's answer is that they are the equivalent to multiple desktops. When seen in that regard you'd only ever have a couple of desktops open but have lots of GUI windows open within each one.
I would say they are similar to in other editors/browsers:
When you see them like that you realise the power of them that you can easily group sets of files (buffers) together e.g. your CSS files, your HTML files and your JS files in different tab pages. Which is actually pretty awesome.
This makes no sense to me. A viewport which although it does have a defined dictionary term, I've only heard referring to Vim windows in the :help window
doc. Viewport is not a term I've ever heard with regards to editors like Sublime Text, Visual Studio, Atom, Notepad++. In fact I'd never heard about it for Vim until I started to try using tab pages.
If you view tab pages like multiple desktops, then referring to a desktop as a single window seems odd.
This possibly makes more sense, the dictionary definition is:
A memory storage facility for temporary use.
So it's like a place where you store a group of buffers.
I didn't initially sound like Sublime Text's concept of a workspace which is a list of all the files that you have open in your project:
the sublime-workspace file, which contains user specific data, such as the open files and the modifications to each.
However thinking about it more, this does actually agree. If you regard a Vim tab page like a Sublime Text project, then it would seem odd to have just one file open in each project and keep switching between projects. Hence why using a tab page to have open only one file is odd.
The :help window
refers to tab pages this way. Plus numerous other answers use the same concept. However until you get your head around what a vim window is, then that's not much use, like building a castle on sand.
As I referred to above, a vim window is the same as a viewport and quiet excellently explained in this linux.com article:
A really useful feature in Vim is the ability to split the viewable area between one or more files, or just to split the window to view two bits of the same file more easily. The Vim documentation refers to this as a viewport or window, interchangeably.
You may already be familiar with this feature if you've ever used Vim's help feature by using :help topic or pressing the F1 key. When you enter help, Vim splits the viewport and opens the help documentation in the top viewport, leaving your document open in the bottom viewport.
I find it odd that a tab page is referred to as a collection of windows instead of a collection of buffers. But I guess you can have two separate tab pages open each with multiple windows all pointing at the same buffer, at least that's what I understand so far.
use className->function(); instead className::function() ;
CREATE UNIQUE NONCLUSTERED INDEX [UIX_COLUMN_NAME]
ON [dbo].[Employee]([Username] ASC) WHERE ([Username] IS NOT NULL)
WITH (ALLOW_PAGE_LOCKS = ON, ALLOW_ROW_LOCKS = ON, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF,
DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, STATISTICS_NORECOMPUTE = OFF, ONLINE = OFF,
MAXDOP = 0) ON [PRIMARY];
Even I come across same problem, not able to find active connections to my_db to kill it but still shows same error. I end up disconnecting all possible SSMS connections for any database on the Server, create a new connection from SSMS and change it to Multi user.
-- Actual Code to change my_db to multi user mode
USE MASTER;
GO
ALTER DATABASE [my_db] SET MULTI_USER
Note: This seems to be a possible bug in SQL Server 2005!
I would like to Add to NeilW's answer. To incorporate a method that resembles the orderby. Add this method as an extension:
public static void Sort<T>(this ObservableCollection<T> collection, Func<T,T> keySelector) where T : IComparable
{
List<T> sorted = collection.OrderBy(keySelector).ToList();
for (int i = 0; i < sorted.Count(); i++)
collection.Move(collection.IndexOf(sorted[i]), i);
}
And use like:
myCollection = new ObservableCollection<MyObject>();
//Sorts in place, on a specific Func<T,T>
myCollection.Sort(x => x.ID);
To support the answers given above, The details of the redis instance can be obtained by
$ redis-cli
$ INFO
This gives all the info you may need
# Server
redis_version:5.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:da75abdfe06a50f8
redis_mode:standalone
os:Linux 5.3.0-51-generic x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:7.5.0
process_id:14126
run_id:adfaeec5683d7381a2a175a2111f6159b6342830
tcp_port:6379
uptime_in_seconds:16860
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:15766886
executable:/tmp/redis-5.0.5/src/redis-server
config_file:
# Clients
connected_clients:22
....More Verbose
The version lies in the second line :)
This worked for me:
mv xyz.war ./tmp
cd tmp
jar -xvf xyz.war
rm -rf WEB-INF/lib/zookeeper-3.4.10.jar
rm -rf xyz.war
jar -cvf xyz.war *
mv xyz.war ../
cd ..
For a box that appears in the center - horizontal & vertical - I got this to work with just one LinearLayout. The answer from Viswanath L was very helpful
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/layout_bg"
android:gravity="center"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:id="@+id/dialog_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="Error"
android:textColor="#000" />
<TextView
android:id="@+id/message_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="10dp"
android:text="Error-Message"
android:textColor="#000" />
<Button
android:id="@+id/dialogButtonOK"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/message_text"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"
android:text="Ok" />
</LinearLayout>
Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.
DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)
name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)
I think you might want something like this
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
Normally i use a class for this:
public class ClassName
{
public string Col1 { get; set; }
public int Col2 { get; set; }
}
Now you can use a loop to fill a list and ToArray
if you really need an array:
ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
FROM some table";
using (var command = new SqlCommand(sql, con))
{
con.Open();
using (var reader = command.ExecuteReader())
{
var list = new List<ClassName>();
while (reader.Read())
list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
allRecords = list.ToArray();
}
}
Note that i've presumed that the first column is a string
and the second an integer
. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY
methods.
You mean staticly define a value, like this:
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
You need to escape the backslash \
:
println yourString.replace("\\", "/")
you can also do this query...!
sqlContext.sql("""
select from_unixtime(unix_timestamp('08/26/2016', 'MM/dd/yyyy'), 'yyyy:MM:dd') as new_format
""").show()
I suggest you to read the Enumeration: Traversing a Collection’s Elements part of the Collections Programming Guide for Cocoa. There is a sample code for your need.
You can't use Microsoft.Office.Interop.Excel without having ms office installed.
Just search in google for some libraries, which allows to modify xls or xlsx:
If you want a deep copy without override while retaining the same obj
reference
obj = _.assign(obj, _.merge(obj, [source]))
Here is a quick and simple solution using PowerShell:
powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"
This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16
to CopyHere
answers all questions with yes.
In conclusion, when you use a local variable of a type that implements IDisposable
, always, without exception, use using
1.
If you use nonlocal IDisposable
variables, then always implement the IDisposable
pattern.
Two simple rules, no exception1. Preventing resource leaks otherwise is a real pain in the *ss.
1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose
explicitly in the finally
block.
My solution:
protected boolean inhibit_spinner = true;
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
if (inhibit_spinner) {
inhibit_spinner = false;
}else {
if (getDataTask != null) getDataTask.cancel(true);
updateData();
}
}
Actually, there is a way. You just need to copy DeviceSupport folder for iOS 7.1 from Older Xcode to the new one. It's located in:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.1
If you don't have the 7.1 files anymore, you can download a previous version of XCode on https://developer.apple.com/download/more/, extract it, and then copy these files to following path
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/
I think you've just made up shorthand syntax for the border:
property there =)
Try simply:
border-right: 1px solid #000;
border-left: 1px solid #000;
Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
You are getting NullReferenceExeption
because of you are using the cmb.SelectedValue
which is null. the comboBox
doesn't know what is the value of your custom class ComboboxItem
, so either do:
ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);
Or better of is use data binding like:
ComboboxItem item1 = new ComboboxItem();
item1.Text = "test";
item1.Value = "123";
ComboboxItem item2 = new ComboboxItem();
item2.Text = "test2";
item2.Value = "456";
List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };
this.comboBox1.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;
Sure. You can add a border to any layout you want. Basically, you need to create a custom drawable and add it as a background to your layout. example:
Create a file called customborder.xml
in your drawable folder:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="20dp"/>
<padding android:left="10dp" android:right="10dp" android:top="10dp" android:bottom="10dp"/>
<stroke android:width="1dp" android:color="#CCCCCC"/>
</shape>
Now apply it as a background to your smaller layout:
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/customborder">
That should do the trick.
Also see:
Important: Use the
( )
parentheses in your search string
While the previous answer is correct there is an important thing to emphasize! All the matched segments in your search string that you want to use in your replacement string must be enclosed by ( )
parentheses, otherwise these matched segments won't be accessible to defined variables such as $1
, $2
or \1
, \2
etc.
For example we want to replace 'em' with 'px' but preserve the digit values:
margin: 10em; /* Expected: margin: 10px */
margin: 2em; /* Expected: margin: 2px */
margin: $1px
or margin: \1px
margin: ([0-9]*)em
// with parenthesesmargin: [0-9]*em
CORRECT CASE EXAMPLE: Using margin: ([0-9]*)em
search string (with parentheses). Enclose the desired matched segment (e.g. $1
or \1
) by ( )
parentheses as following:
margin: ([0-9]*)em
(with parentheses)margin: $1px
or margin: \1px
margin: 10px;
margin: 2px;
INCORRECT CASE EXAMPLE: Using margin: [0-9]*em
search string (without parentheses). The following regex pattern will match the desired lines but matched segments will not be available in replaced string as variables such as $1
or \1
:
margin: [0-9]*em
(without parentheses)margin: $1px
or margin: \1px
margin: px; /* `$1` is undefined */
margin: px; /* `$1` is undefined */
I've been frustrated by this myself and finally solved it. As Romain Guy hinted to, there's another state, "android:state_selected"
, that you must use. Use a state drawable for the background of your list item, and use a different state drawable for listSelector
of your list:
list_row_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="@drawable/listitem_background"
>
...
</LinearLayout>
listitem_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="@color/android:transparent" />
<item android:drawable="@drawable/listitem_normal" />
</selector>
layout.xml that includes the ListView:
...
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/listitem_selector"
/>
...
listitem_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/listitem_pressed" />
<item android:state_focused="true" android:drawable="@drawable/listitem_selected" />
</selector>
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
If you'd rather not use jQuery, this can be achieved with CSS3
@-webkit-keyframes blink {
from { opacity: 1.0; }
to { opacity: 0.0; }
}
blink {
-webkit-animation-name: blink;
-webkit-animation-iteration-count: infinite;
-webkit-animation-timing-function: cubic-bezier(1.0,0,0,1.0);
-webkit-animation-duration: 1s;
}
Seems to work in Chrome, though I thought I heard a slight sobbing noise.
I tried this:
if(capital !== null){
//Capital has something
}
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
I was getting this error due to the BasicHttpBinding not sending a compatible messageVersion to the service i was calling. My solution was to use a custom binding like below
<bindings>
<customBinding>
<binding name="Soap11UserNameOverTransport" openTimeout="00:01:00" receiveTimeout="00:1:00" >
<security authenticationMode="UserNameOverTransport">
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10" writeEncoding="utf-8" />
<httpsTransport></httpsTransport>
</binding>
</customBinding>
</bindings>
My Angular 2 project doesn't have the "main.ts" file mentioned other answers, but it does have a "boot.ts" file, which seems to be about the same thing. (The difference is probably due to different versions of Angular.)
Adding these two lines after the last import
directive in "boot.ts" worked for me:
import { enableProdMode } from "@angular/core";
enableProdMode();
Let me guess
Your initial declaration of class PUBLICClass
was not public, then you made it `Public', can you try to clean and rebuild your project ?
This is an old question, but is high ranked on Google. I almost can't believe on the highest voted answers, because running a node.js process inside a screen session, with the &
or even with the nohup
flag -- all of them -- are just workarounds.
Specially the screen/tmux solution, which should really be considered an amateur solution. Screen and Tmux are not meant to keep processes running, but for multiplexing terminal sessions. It's fine, when you are running a script on your server and want to disconnect. But for a node.js server your don't want your process to be attached to a terminal session. This is too fragile. To keep things running you need to daemonize the process!
There are plenty of good tools to do that.
PM2: http://pm2.keymetrics.io/
# basic usage
$ npm install pm2 -g
$ pm2 start server.js
# you can even define how many processes you want in cluster mode:
$ pm2 start server.js -i 4
# you can start various processes, with complex startup settings
# using an ecosystem.json file (with env variables, custom args, etc):
$ pm2 start ecosystem.json
One big advantage I see in favor of PM2 is that it can generate the system startup script to make the process persist between restarts:
$ pm2 startup [platform]
Where platform
can be ubuntu|centos|redhat|gentoo|systemd|darwin|amazon
.
forever.js: https://github.com/foreverjs/forever
# basic usage
$ npm install forever -g
$ forever start app.js
# you can run from a json configuration as well, for
# more complex environments or multi-apps
$ forever start development.json
Init scripts:
I'm not go into detail about how to write a init script, because I'm not an expert in this subject and it'd be too long for this answer, but basically they are simple shell scripts, triggered by OS events. You can read more about this here
Docker:
Just run your server in a Docker container with -d
option and, voilá, you have a daemonized node.js server!
Here is a sample Dockerfile (from node.js official guide):
FROM node:argon
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 8080
CMD [ "npm", "start" ]
Then build your image and run your container:
$ docker build -t <your username>/node-web-app .
$ docker run -p 49160:8080 -d <your username>/node-web-app
Hope this helps somebody landing on this page. Always use the proper tool for the job. It'll save you a lot of headaches and over hours!
You can directly use time.Unix function of time which converts the unix time stamp to UTC
package main
import (
"fmt"
"time"
)
func main() {
unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc
unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format
fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}
Output
unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z
Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd
var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;
For me in sierra version
copy the default configuration at:
/usr/local/Cellar/mysql/5.6.27/support-files/my-default.cnf
to
/usr/local/Cellar/mysql/5.6.27/my.cnf
Note for zsh users: replace all references to ~/.bash_profile
with ~/.zshrc
.
This is the easiest way and will provide automatic updates.
Install the homebrew package manager
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
Install adb
brew install android-platform-tools
Start using adb
adb devices
This is the easiest way to get a manual installation of ADB and Fastboot.
Delete your old installation (optional)
rm -rf ~/.android-sdk-macosx/
Navigate to https://developer.android.com/studio/releases/platform-tools.html and click on the SDK Platform-Tools for Mac
link.
Go to your Downloads folder
cd ~/Downloads/
Unzip the tools you downloaded
unzip platform-tools-latest*.zip
Move them somewhere you won't accidentally delete them
mkdir ~/.android-sdk-macosx
mv platform-tools/ ~/.android-sdk-macosx/platform-tools
Add platform-tools
to your path
echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
Refresh your bash profile (or restart your terminal app)
source ~/.bash_profile
Start using adb
adb devices
Delete your old installation (optional)
rm -rf ~/.android-sdk-macosx/
Download the Mac SDK Tools from the Android developer site under "Get just the command line tools". Make sure you save them to your Downloads folder.
Go to your Downloads folder
cd ~/Downloads/
Unzip the tools you downloaded
unzip tools_r*-macosx.zip
Move them somewhere you won't accidentally delete them
mkdir ~/.android-sdk-macosx
mv tools/ ~/.android-sdk-macosx/tools
Run the SDK Manager
sh ~/.android-sdk-macosx/tools/android
Uncheck everything but Android SDK Platform-tools
(optional)
Install Packages
, accept licenses, click Install
. Close the SDK Manager window.Add platform-tools
to your path
echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
Refresh your bash profile (or restart your terminal app)
source ~/.bash_profile
Start using adb
adb devices
export
makes the variable available to sub-processes.
That is,
export name=value
means that the variable name is available to any process you run from that shell process. If you want a process to make use of this variable, use export
, and run the process from that shell.
name=value
means the variable scope is restricted to the shell, and is not available to any other process. You would use this for (say) loop variables, temporary variables etc.
It's important to note that exporting a variable doesn't make it available to parent processes. That is, specifying and exporting a variable in a spawned process doesn't make it available in the process that launched it.
try using max-width: 100%;
on your canvas.
canvas {
max-width: 100%;
}
I'm using the following trick to stop HTML5 video. pause() the video on modal close and set currentTime = 0;
<script>
var video = document.getElementById("myVideoPlayer");
function stopVideo(){
video.pause();
video.currentTime = 0;
}
</script>
Now you can use stopVideo() method to stop HTML5 video. Like,
$("#stop").on('click', function(){
stopVideo();
});
Sort them and use comm
:
comm -23 <(sort a.txt) <(sort b.txt)
comm
compares (sorted) input files and by default outputs three columns: lines that are unique to a, lines that are unique to b, and lines that are present in both. By specifying -1
, -2
and/or -3
you can suppress the corresponding output. Therefore comm -23 a b
lists only the entries that are unique to a. I use the <(...)
syntax to sort the files on the fly, if they are already sorted you don't need this.
You can add these single quotes with template literals:
var text = "http://example.com"_x000D_
var quoteText = `'${text}'`_x000D_
_x000D_
console.log(quoteText)
_x000D_
Docs are here. Browsers that support template literals listed here.
You're pretty much right about cout
and cin
. They are objects (not functions) defined inside the std
namespace. Here are their declarations as defined by the C++ standard:
Header
<iostream>
synopsis#include <ios> #include <streambuf> #include <istream> #include <ostream> namespace std { extern istream cin; extern ostream cout; extern ostream cerr; extern ostream clog; extern wistream wcin; extern wostream wcout; extern wostream wcerr; extern wostream wclog; }
::
is known as the scope resolution operator. The names cout
and cin
are defined within std
, so we have to qualify their names with std::
.
Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:
class foo
{
public:
foo();
void bar();
};
The constructor named foo
is a member of the class named foo
. They have the same name because its the constructor. The function bar
is also a member of foo
.
Because they are members of foo
, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar
outside the class, you need to do it like so:
foo::foo()
{
// Implement the constructor
}
void foo::bar()
{
// Implement bar
}
This is because they are being defined outside the class. If you had not put the foo::
qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo
. For example, this is entirely different bar
:
void bar()
{
// Implement different bar
}
It's allowed to have the same name as the function in the foo
class because it's in a different scope. This bar
is in the global scope, whereas the other bar
belonged to the foo
class.
the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already
public void showHideCardPreview(int id) {
FragmentManager fm = getSupportFragmentManager();
Bundle b = new Bundle();
b.putInt(Constants.CARD, id);
cardPreviewFragment.setArguments(b);
FragmentTransaction ft = fm.beginTransaction()
.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
if (!cardPreviewFragment.isAdded()){
ft.add(R.id.full_screen_container, cardPreviewFragment);
ft.show(cardPreviewFragment);
} else {
if (cardPreviewFragment.isHidden()) {
Log.d(TAG,"++++++++++++++++++++ show");
ft.show(cardPreviewFragment);
} else {
Log.d(TAG,"++++++++++++++++++++ hide");
ft.hide(cardPreviewFragment);
}
}
ft.commit();
}
Linux.
$ apt-get install beep
$ python
>>> os.system("beep -f 555 -l 460")
OR
$ beep -f 659 -l 460 -n -f 784 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 880 -l 230 -n -f 659 -l 230 -n -f 587 -l 230 -n -f 659 -l 460 -n -f 988 -l 340 -n -f 659 -l 230 -n -f 659 -l 110 -n -f 1047-l 230 -n -f 988 -l 230 -n -f 784 -l 230 -n -f 659 -l 230 -n -f 988 -l 230 -n -f 1318 -l 230 -n -f 659 -l 110 -n -f 587 -l 230 -n -f 587 -l 110 -n -f 494 -l 230 -n -f 740 -l 230 -n -f 659 -l 460
For me save_queries
option was turned off so,
$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;
Ref: Can't get result from $this->db->last_query(); codeigniter
If none of the answers worked out for you, try this,
Hyper-V might not be disabled If you have windows 10 features such as Device Guard and Credential Guard is enabled, it can prevent Hyper-V from being completely disabled.
The Device Guard and Credential Guard hardware readiness tool released by Microsoft can disable the said Windows 10 features along with Hyper-V:
Download it here, https://www.microsoft.com/en-us/download/details.aspx?id=53337
Download the latest version of the Device Guard and Credential Guard hardware readiness tool. Unzip Open the Command Prompt using Run as administrator @powershell -ExecutionPolicy RemoteSigned -Command "X:\path\to\dgreadiness_v3.6\DG_Readiness_Tool_v3.6.ps1 -Disable" Reboot.
Renames all .pdf
files based on current system date. For example a file named Gross Profit.pdf
is renamed to Gross Profit 2014-07-31.pdf
. If you run it tomorrow, it will rename it to Gross Profit 2014-08-01.pdf
.
You could replace the ?
with the report name Gross Profit
, but it will only rename the one report. The ?
renames everything in the Conduit
folder. The reason there are so many ?
, is that some .pdf
s have long names. If you just put 12 ?
s, then any name longer than 12 characters will be clipped off at the 13th character. Try it with 1 ?
, then try it with many ?
s. The ?
length should be a little longer or as long as the longest report name.
@ECHO OFF
SET NETWORKSOURCE=\\flcorpfile\shared\"SHORE Reports"\2014\Conduit
REN %NETWORKSOURCE%\*.pdf "????????????????????????????????????????????????? %date:~-4,4%-%date:~-10,2%-%date:~7,2%.pdf"
Not difficult, check this.
<button @click="disabled = !disabled">Toggle Enable</button>
<input type="text" id="name" class="form-control" name="name" v-model="form.name" :disabled="disabled">
Some of the answers here assume you are on master branch before you decided to checkout an older commit. This is not always the case.
git checkout -
Will point you back to the branch you were previously on (regardless if it was master or not).
Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot
, catplot
/ factorplot
, jointplot
) you can and should specify this within the arguments using height
and aspect
.
sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.
I was able to fix this by doing two things, though you may not have to do step 1.
copy from cygwin ssh.exe and all cyg*.dll into Git's bin directory (this may not be necessary but it is a step I took but this alone did not fix things)
follow the steps from: http://zylstra.wordpress.com/2008/08/29/overcome-herokus-permission-denied-publickey-problem/
I added some details to my ~/.ssh/config file:
Host heroku.com
Hostname heroku.com
Port 22
IdentitiesOnly yes
IdentityFile ~/.ssh/id_heroku
TCPKeepAlive yes
User brandon
I had to use User as my email address for heroku.com Note: this means you need to create a key, I followed this to create the key and when it prompts for the name of the key, be sure to specify id_heroku http://help.github.com/win-set-up-git/
Here is where you went wrong:
this.result = http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result.json());
it should be:
http.get('friends.json')
.map(response => response.json())
.subscribe(result => this.result =result);
or
http.get('friends.json')
.subscribe(result => this.result =result.json());
You have made two mistakes:
1- You assigned the observable itself to this.result
. When you actually wanted to assign the list of friends to this.result
. The correct way to do it is:
you subscribe to the observable. .subscribe
is the function that actually executes the observable. It takes three callback parameters as follow:
.subscribe(success, failure, complete);
for example:
.subscribe(
function(response) { console.log("Success Response" + response)},
function(error) { console.log("Error happened" + error)},
function() { console.log("the subscription is completed")}
);
Usually, you take the results from the success callback and assign it to your variable.
the error callback is self explanatory.
the complete callback is used to determine that you have received the last results without any errors.
On your plunker, the complete callback will always be called after either the success or the error callback.
2- The second mistake, you called .json()
on .map(res => res.json())
, then you called it again on the success callback of the observable.
.map()
is a transformer that will transform the result to whatever you return (in your case .json()
) before it's passed to the success callback
you should called it once on either one of them.
Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:
wget -q --tries=10 --timeout=20 --spider http://google.com
if (( $? != 0 )); then
echo "Sorry you are Offline"
exit 1
fi
Notice how instead of -ne
, you can just use !=
. In an arithmetic context, we don't even have to prepend $
to parameters, i.e.,
var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"
works perfectly fine. This doesn't appply to the $?
special parameter, though.
Further, since (( ... ))
evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to
if (( $? )); then
but this might confuse more people than the keystrokes saved are worth.
The (( ... ))
construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).
This all being said, it's better to avoid $?
altogether in my opinion, as in Cole's answer and Steven's answer.
We can also use RxJava to move network operations to a background thread. And it's fairly simple as well.
webService.doSomething(someData)
.subscribeOn(Schedulers.newThread())-- This for background thread
.observeOn(AndroidSchedulers.mainThread()) -- for callback on UI
.subscribe(result -> resultText.setText("It worked!"),
e -> handleError(e));
You can do a lot more stuff with RxJava.Here are some links for RxJava. Feel free to dig in.
You want to do this:
select * from
(
SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
UNION
SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered
Update
I noticed that even though you have two different tables, you join the IDs, that means, if you have 1
in both tables, you are getting only one occurrence. If that's the desired behavior, you should stick to UNION
. If not, change to UNION ALL
.
So I also notice that if you change to the code I proposed, You would start getting both 1
and 2
(from both a
and b
). In that case, you might want to change the proposed code to:
select distinct id from
(
SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
UNION
SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered
I have setup a DataFrame
with a few simple strings in it's columns:
>>> df
a b
0 a g
1 b h
2 d a
3 e e
You can concatenate the columns you are interested in and call unique
function:
>>> pandas.concat([df['a'], df['b']]).unique()
array(['a', 'b', 'd', 'e', 'g', 'h'], dtype=object)
If you interested in running Entity Framework with MySql on mono/linux/macos, this might be helpful https://iyalovoi.wordpress.com/2015/04/06/entity-framework-with-mysql-on-mac-os/
Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.
The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.
Another option if you are using Guava Collections is Ints.indexOf
// Perfect storm:
final int needle = 42;
final int[] haystack = [1, 2, 3, 42];
// Spoiler alert: index == 3
final int index = Ints.indexOf(haystack, needle);
This is a great choice when space, time and code reuse are at a premium. It is also very terse.
<form class="col-xs-12" method="post" action="/News/AddNews" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="image" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary col-xs-12">Add</button>
</div>
</form>
My Action Is
[HttpPost]
public IActionResult AddNews(IFormFile image)
{
Tbl_News tbl_News = new Tbl_News();
if (image!=null)
{
//Set Key Name
string ImageName= Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//Get url To Save
string SavePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot/img",ImageName);
using(var stream=new FileStream(SavePath, FileMode.Create))
{
image.CopyTo(stream);
}
}
return View();
}
great one... now i have stopped using % he he he... except for the main container as shown below:
<div id="divContainer">
<div id="divHeader">
</div>
<div id="divContentArea">
<div id="divContentLeft">
</div>
<div id="divContentRight">
</div>
</div>
<div id="divFooter">
</div>
</div>
and here is the css:
#divContainer {
width: 100%;
height: 100%;
}
#divHeader {
position: absolute;
left: 0px;
top: 0px;
right: 0px;
height: 28px;
}
#divContentArea {
position: absolute;
left: 0px;
top: 30px;
right: 0px;
bottom: 30px;
}
#divContentLeft {
position: absolute;
top: 0px;
left: 0px;
width: 250px;
bottom: 0px;
}
#divContentRight {
position: absolute;
top: 0px;
left: 254px;
right: 0px;
bottom: 0px;
}
#divFooter {
position: absolute;
height: 28px;
left: 0px;
bottom: 0px;
right: 0px;
}
i tested this in all known browsers and is working fine. Are there any drawbacks using this way?
When using literal strings (start with @") this might be easier
char tab = '\u0009';
string A = "Apple";
string B = "Bob";
string myStr = String.Format(@"{0}:{1}{2}", A, tab, B);
Would result in Apple:<tab>Bob
the html:
<a class="xyz">your content</a>
the css:
.xyz{
display: block;
}
This will make the anchor be a block level element like a div.
Guys in some PC's this issue is caused by antivirus programs AFTER upgrading to the latest android studio and gradle version. In my case I tore my system apart troubleshooting everything only to find out that Commodo Internet security was responsible for not letting the gradle daemon run.
After safelisting the process everything runs smoothly. PLEASE NOTE that everything was OK before updating. The issue came up only after the update without changing anything in the antivirus/firewall program.
http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx
Console.WriteLine("typeField is a {0}", typeField.GetType());
which would give you something like
typeField is a String
typeField is a DateTime
or
http://msdn.microsoft.com/en-us/library/58918ffs(v=vs.71).aspx
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
q = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5]
vm = [-1, -1, -1, -1,1,2,3,1]
p = []
for v in vm:
if v in q:
p.append(q.index(v))
else:
p.append(99999)
print p
p = [q.index(v) if v in q else 99999 for v in vm]
print p
Output:
[99999, 99999, 99999, 99999, 0, 1, 2, 0]
[99999, 99999, 99999, 99999, 0, 1, 2, 0]
Instead of using append()
in the list comprehension you can reference the p as direct output, and use q.index(v)
and 99999
in the LC.
Not sure if this is intentional but note that q.index(v)
will find just the first occurrence of v
, even tho you have several in q
. If you want to get the index of all v
in q
, consider using a enumerator
and a list of already visited indexes
Something in those lines(pseudo-code):
visited = []
for i, v in enumerator(vm):
if i not in visited:
p.append(q.index(v))
else:
p.append(q.index(v,max(visited))) # this line should only check for v in q after the index of max(visited)
visited.append(i)
Is there a way to get a list of all the keys in a Go language map?
ks := reflect.ValueOf(m).MapKeys()
how do I iterate over all the keys?
Use the accepted answer:
for k, _ := range m { ... }
adb logcat -c
Logcat options are documented here: http://developer.android.com/tools/help/logcat.html
Some steps you can try. (its how we do it at my workplace)
Hope that helps.
I too was struggling with nested views in Angular.
Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.
Here is an example application that uses multiple levels of views nesting
app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");
$stateProvider
.state('view1', {
url: '/view1',
templateUrl: 'partials/view1.html',
controller: 'view1.MainController'
})
.state('view1.nestedViews', {
url: '/view1',
views: {
'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
}
})
.state('view2', {
url: '/view2',
})
.state('view3', {
url: '/view3',
})
.state('view4', {
url: '/view4',
});
});
As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.
If you don't need it to be human-readable/editable, the easiest solution is to just use pickle
.
To write:
with open(the_filename, 'wb') as f:
pickle.dump(my_list, f)
To read:
with open(the_filename, 'rb') as f:
my_list = pickle.load(f)
If you do need them to be human-readable, we need more information.
If my_list
is guaranteed to be a list of strings with no embedded newlines, just write them one per line:
with open(the_filename, 'w') as f:
for s in my_list:
f.write(s + '\n')
with open(the_filename, 'r') as f:
my_list = [line.rstrip('\n') for line in f]
If they're Unicode strings rather than byte strings, you'll want to encode
them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)
If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.
Let's use unicode-escape
here to solve both of the above problems at once:
with open(the_filename, 'w') as f:
for s in my_list:
f.write((s + u'\n').encode('unicode-escape'))
with open(the_filename, 'r') as f:
my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]
You can also use the 3.x-style solution in 2.x, with either the codecs
module or the io
module:*
import io
with io.open(the_filename, 'w', encoding='unicode-escape') as f:
f.writelines(line + u'\n' for line in my_list)
with open(the_filename, 'r') as f:
my_list = [line.rstrip(u'\n') for line in f]
* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs
; if not, use io
.
You should add the resources in a library project as per http://developer.android.com/tools/support-library/setup.html
Section > Adding libraries with resources
You then add the android-support-v7-appcompat
library in your workspace and then add it as a reference to your app project.
Defining all the resources in your app project will also work (but there are a lot of definitions to add and you have missed some of them), and it is not the recommended approach.
I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:
##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))
All that's left is a simple ggplot command:
ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
scale_colour_manual(values=c("red","green","blue"))
Example plot
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
Use the Apache BooleanUtils.
(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)
Don't reinvent the wheel. Leverage what's already been built and use isTrue()
:
BooleanUtils.isTrue( bool );
Checks if a Boolean
value is true, handling null
by returning false
.
If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans
and Strings
. I suggest you peruse the various Apache libraries and see what they already offer.
This is an easy way to prevent the click event from moving forward to the next component and then call your yourFunction.
<Button onClick={(e)=> {e.stopPropagation(); yourFunction(someParam)}}>Delete</Button>
With Apache Commons Lang3 lib is it very easy.
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
public String getName(String text) {
return StringUtils.remove(WordUtils.capitalizeFully(text, '_'), "_");
}
Example:
getName("SOME_CONSTANT");
Gives:
"SomeConstant"
For a static library, the code is extracted from the library by the linker and used to build the the final executable at the point you compile/build your application. The final executable has no dependencies on the library at run time
For a shared library, the compiler/linker checks that the names you link with exist in the library when the application is built, but doesn't move their code into the application. At run time, the shared library must be available.
The C programming language itself has no concept of either static or shared libraries - they are completely an implementation feature.
Personally, I much prefer to use static libraries, as it makes software distribution simpler. However, this is an opinion over which much (figurative) blood has been shed in the past.
I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set sys.path
in the invoke scripts for standalone projects.
However sys.path.append
isn't the way to do it. You can easily get duplicates, and it doesn't sort out .pth
files. Better (and more readable): site.addsitedir
.
And script.py
wouldn't normally be the more appropriate place to do it, as it's inside the package you want to make available on the path. Library modules should certainly not be touching sys.path
themselves. Instead, you'd normally have a hashbanged-script outside the package that you use to instantiate and run the app, and it's in this trivial wrapper script you'd put deployment details like sys.path
-frobbing.
The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.
To get around this I created a empty Div right at the top of my HTML(outside my main container)
<div id="max-width"></div>
In css I set this div to display none
#max-width {
display: none;
}
In my JS created a function
var hasSwitched = function () {
var maxWidth = parseInt($('#max-width').css('max-width'), 10);
return !isNaN(maxWidth);
};
So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following
if (!hasSwitched()) { Your code
}
else{ your code
}
By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.
To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys
The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.
print(*3*('-',), sep='_')
This should work:
txtfarmersize = Convert.ToInt32(reader["farmsize"]);
You can make a hyperlink in Telegram by writing an URL and send the message. Using Telegram Bot APIs you can send a clickable URL in two ways:
Markdown:
[This is an example](https://example.com)
HTML:
<a href="https://example.com">This is an example</a>
In both cases you will have:
EDIT: In new version of Telegram clients you can do that, see above answers.
I found a problem while working with a jQuery Mobile application, where in some cases my Meta header tag wouldn't achieve a redirection properly (jQuery Mobile doesn't read headers automatically for each page so putting JavaScript there is also ineffective unless wrapping it in complexity). I found the easiest solution in this case was to put the JavaScript redirection directly into the body of the document, as follows:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="0;url=myURL" />
</head>
<body>
<p>You are not logged in!</p>
<script language="javascript">
window.location = "myURL";
</script>
</body>
</html>
This seems to work in every case for me.
Pull from the repository to a new directory, then rename the old one to old_crufty
, and the new one to my_real_webserver_directory
, and you're good to go.
If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.
AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.
As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.
So AArch64 and ARM64 refer to the same thing.
From http://docs.python-requests.org/en/latest/user/quickstart/
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)
You just need to create a dict with your headers (key: value pairs where the key is the name of the header and the value is, well, the value of the pair) and pass that dict to the headers parameter on the .get
or .post
method.
So more specific to your question:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)
You could just use the FolderBrowserDialog
class from the System.Windows.Forms
namespace.
You could use iotop. It doesn't rely on a kernel patch. It Works with stock Ubuntu kernel
There is a package for it in the Ubuntu repos. You can install it using
sudo apt-get install iotop
One way is to simply treat binary files as text anyway, with grep --text
but this may well result in binary information being sent to your terminal. That's not really a good idea if you're running a terminal that interprets the output stream (such as VT/DEC or many others).
Alternatively, you can send your file through tr
with the following command:
tr '[\000-\011\013-\037\177-\377]' '.' <test.log | grep whatever
This will change anything less than a space character (except newline) and anything greater than 126, into a .
character, leaving only the printables.
If you want every "illegal" character replaced by a different one, you can use something like the following C program, a classic standard input filter:
#include<stdio.h>
int main (void) {
int ch;
while ((ch = getchar()) != EOF) {
if ((ch == '\n') || ((ch >= ' ') && (ch <= '~'))) {
putchar (ch);
} else {
printf ("{{%02x}}", ch);
}
}
return 0;
}
This will give you {{NN}}
, where NN
is the hex code for the character. You can simply adjust the printf
for whatever style of output you want.
You can see that program in action here, where it:
pax$ printf 'Hello,\tBob\nGoodbye, Bob\n' | ./filterProg
Hello,{{09}}Bob
Goodbye, Bob
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});