I had a similar issue while working with Jupyter. I was trying to copy files from one directory to another using copy function of shutil. The problem was that I had forgotten to import the package.(Silly) But instead of python giving import error, it gave this error.
Solved by adding:
from shutil import copy
When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.
The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.
With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.
For example:
import os
testval = ['c:','c:\\','d:','j:','jr:','data:']
for t in testval:
print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value: c: , join to "folder" c:folder test value: c:\ , join to "folder" c:\folder test value: d: , join to "folder" d:folder test value: j: , join to "folder" j:folder test value: jr: , join to "folder" jr:\folder test value: data: , join to "folder" data:\folder
A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive
comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t
.
Test:
for t in testval:
corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c: corrected: c:\ join corrected-> c:\folder original: c:\ corrected: c:\ join corrected-> c:\folder original: d: corrected: d:\ join corrected-> d:\folder original: j: corrected: j:\ join corrected-> j:\folder original: jr: corrected: jr: join corrected-> jr:\folder original: data: corrected: data: join corrected-> data:\folder
it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea. See also Os.path : can you explain this behavior? for interesting details on systems other then windows.
Tried to specify dll path in different ways (proposed by @markm), but nothing has worked for me. Fixed the problem by copying dll into script folder. It's not a good solution, but ok for my purposes.
Just found sys.executable
- the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)
import sys
import subprocess
theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()
If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER
This is my project error when I try to vilidated.
Finally follow this ANSWER, error solved.
Two possibilities are there when AJAX request gets dropped (if not Cross-Origin request):
Solution for 1):
Add return false;
or e.preventDefault();
in the event handler.
Solution for 2): Add timeout option while forming the AJAX request. Example below.
$.ajax({
type: 'POST',
url: url,
timeout: 86400,
data: data,
success: success,
dataType: dataType
});
For Cross-origin requests, check Cross-Origin Resource Sharing (CORS) HTTP headers.
You can use BOOL, BOOLEAN data type for storing boolean values.
These types are synonyms for TINYINT(1)
However, the BIT(1) data type makes more sense to store a boolean value (either true[1] or false[0]) but TINYINT(1) is easier to work with when you're outputting the data, querying and so on and to achieve interoperability between MySQL and other databases. You can also check this answer or thread.
MySQL also converts BOOL, BOOLEAN data types to TINYINT(1).
Further, read documentation
Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window
)
This is an example of his idea:
Html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="init.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
</script>
<script src="script.js"></script>
</head>
<body>
<h1>Hello !</h1>
</body>
</html>
init.js (Based on this answer)
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function(i) {
return _args[i];
}
};
}());
script.js
// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);
alert(a);
Here's the plnkr. Hope it help !
foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"
This works because the #
operator computes the length of the list. The empty list has length 0, etc.
If you're using Lua 5.3+, then you can do almost exactly what you wanted:
foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"
Expressions are not statements in Lua and they need to be used somehow.
There's time.ParseDuration
which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.
E.g. when you need to substract an hour and a half, you can do that like so:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
duration, _ := time.ParseDuration("-1.5h")
then := now.Add(duration)
fmt.Println("then:", then)
}
There are basically two alternatives, using setLength(0)
to reset the StringBuilder or creating a new one in each iteration. Both can have pros and cons depending on the usage.
If you know the expected capacity of the StringBuilder beforehand, creating a new one each time should be just as fast as setting a new length. It will also help the garbage collector, since each StringBuilder will be relatively short-lived and the gc is optimized for that.
When you don't know the capacity, reusing the same StringBuilder might be faster. Each time you exceed the capacity when appending, a new backing array has to be allocated and the previous content has to be copied. By reusing the same StringBuilder, it will reach the needed capacity after some iterations and there won't be any copying thereafter.
You're almost there. Simply use:
//form[@id='myform']//input[@type='submit']
The //
shortcut can also be used inside an expression.
With PHP you just can handle server-side stuff. What you can do is print this in your iframe:
parent.window.location.reload();
I can't see anything obviously wrong, but perhaps a different approach might help you debug it?
You could try specify your datasource in the per-application-context instead of the global tomcat one.
You can do this by creating a src/main/webapp/META-INF/context.xml (I'm assuming you're using the standard maven directory structure - if not, then the META-INF folder should be a sibling of your WEB-INF directory). The contents of the META-INF/context.xml file would look something like:
<?xml version="1.0" encoding="UTF-8"?>
<Context [optional other attributes as required]>
<Resource name="jdbc/PollDatasource" auth="Container"
type="javax.sql.DataSource" driverClassName="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail" maxActive="20" maxIdle="10" maxWait="-1"/>
</Context>
Obviously the path and docBase would need to match your application's specific details.
Using this approach, you don't have to specify the datasource details in Tomcat's context.xml file. Although, if you have multiple applications talking to the same database, then your approach makes more sense.
At any rate, give this a whirl and see if it makes any difference. It might give us a clue as to what is going wrong with your approach.
First argument in update
method is SyntheticEvent
object that contains common properties and methods to any event
, it is not reference to React component where there is property props
.
if you need pass argument to update method you can do it like this
onClick={ (e) => this.props.onClick(e, 'home', 'Home') }
and get these arguments inside update
method
update(e, space, txt){
console.log(e.target, space, txt);
}
event.target
gives you the native DOMNode
, then you need to use the regular DOM APIs to access attributes. For instance getAttribute
or dataset
<button
data-space="home"
className="home"
data-txt="Home"
onClick={ this.props.onClick }
/>
Button
</button>
onClick(e) {
console.log(e.target.dataset.txt, e.target.dataset.space);
}
To format the code in Visual Studio when you want, press: (Ctrl + K) & (Ctrl + F)
The auto formatting rules can be found and changed in: Tools/Options --> (Left sidebar): Text Editor / CSS (or whatever other language you want to change)
For the CSS language the options are unfortunately very limited. You can also make some changes in: .../ Text Editor / All Languages
CultureInfo.CurrentCulture.TextInfo.ToTitleCase("hello world");
string valueStr = "title, genre, director, actor";
var vals = valueStr.Split(',')[0];
vals will give you the title
If you know your database has been updated and you want to just refresh your ViewController (which was my case). I didn't find another solution but what I did was when my database updated, I called:
[self viewDidLoad];
again, and it worked. Remember if you override other viewWillAppear or loadView then call them too in same order. like.
[self viewDidLoad]; [self viewWillAppear:YES];
I think there should be a more specific solution like refresh button in browser.
If the need is to convert "òéisöç->oeisoc", you can use this a starting point :
public class AsciiUtils {
private static final String PLAIN_ASCII =
"AaEeIiOoUu" // grave
+ "AaEeIiOoUuYy" // acute
+ "AaEeIiOoUuYy" // circumflex
+ "AaOoNn" // tilde
+ "AaEeIiOoUuYy" // umlaut
+ "Aa" // ring
+ "Cc" // cedilla
+ "OoUu" // double acute
;
private static final String UNICODE =
"\u00C0\u00E0\u00C8\u00E8\u00CC\u00EC\u00D2\u00F2\u00D9\u00F9"
+ "\u00C1\u00E1\u00C9\u00E9\u00CD\u00ED\u00D3\u00F3\u00DA\u00FA\u00DD\u00FD"
+ "\u00C2\u00E2\u00CA\u00EA\u00CE\u00EE\u00D4\u00F4\u00DB\u00FB\u0176\u0177"
+ "\u00C3\u00E3\u00D5\u00F5\u00D1\u00F1"
+ "\u00C4\u00E4\u00CB\u00EB\u00CF\u00EF\u00D6\u00F6\u00DC\u00FC\u0178\u00FF"
+ "\u00C5\u00E5"
+ "\u00C7\u00E7"
+ "\u0150\u0151\u0170\u0171"
;
// private constructor, can't be instanciated!
private AsciiUtils() { }
// remove accentued from a string and replace with ascii equivalent
public static String convertNonAscii(String s) {
if (s == null) return null;
StringBuilder sb = new StringBuilder();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
int pos = UNICODE.indexOf(c);
if (pos > -1){
sb.append(PLAIN_ASCII.charAt(pos));
}
else {
sb.append(c);
}
}
return sb.toString();
}
public static void main(String args[]) {
String s =
"The result : È,É,Ê,Ë,Û,Ù,Ï,Î,À,Â,Ô,è,é,ê,ë,û,ù,ï,î,à,â,ô,ç";
System.out.println(AsciiUtils.convertNonAscii(s));
// output :
// The result : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o,c
}
}
The JDK 1.6 provides the java.text.Normalizer class that can be used for this task.
See an example here
A jQuery plugin could be found here: Auto-populating Select Boxes using jQuery & AJAX.
You can also get control of grand parent index by the following code
$parent.$parent.$index
Script to check the Backup and Restore progress in SQL Server:
Many times it happens that your backup (or restore) activity has been started by another Database Administrator or by a job, and you cannot use the GUI anything else to check the progress of that Backup / Restore.
By combining multiple commands, I have generated below script which can give us a summary of current backups and restores which are happening on the server.
select
r.session_id,
r.blocking_session_id,
db_name(database_id) as [DatabaseName],
r.command,
[SQL_QUERY_TEXT] = Substring(Query.TEXT, (r.statement_start_offset / 2) + 1, (
(
CASE r.statement_end_offset
WHEN - 1
THEN Datalength(Query.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset
) / 2
) + 1),
[SP_Name] =Coalesce(Quotename(Db_name(Query.dbid)) + N'.' + Quotename(Object_schema_name(Query.objectid, Query.dbid)) + N'.' +
Quotename(Object_name(Query.objectid, Query.dbid)), ''),
r.percent_complete,
start_time,
CONVERT(VARCHAR(20), DATEADD(ms, [estimated_completion_time],
GETDATE()), 20) AS [ETA_COMPLETION_TIME],
CONVERT(NUMERIC(6, 2), r.[total_elapsed_time] / 1000.0 / 60.0) AS [Elapsed_MIN],
CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0) AS [Remaning_ETA_MIN],
CONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0/ 60.0) AS [ETA_Hours],
wait_type,
wait_time/1000 as Wait_Time_Sec,
wait_resource
from sys.dm_exec_requests r
cross apply sys.fn_get_sql(r.sql_handle) as Query where r.session_id>50 and command IN ('RESTORE DATABASE','BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG')
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
You don't have to quit Intellij completely to make this work. Simply close the project that you have open. (You can open any another project to avoid closing it completely)
Go to the directory where you have your project installed and delete the ".idea" folder.
Reopen the Project.
That should fix it. It worked for me in May 2018.
To get the "first" value:
map.values().toArray()[0]
To get the value of the "first" key:
map.get(map.keySet().toArray()[0])
Note: Above code tested and works.
I say "first" because HashMap entries are not ordered.
However, a LinkedHashMap iterates its entries in the same order as they were inserted - you could use that for your map implementation if insertion order is important.
use this way in xml
<TextView
android:id="@+id/myText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Time is precious, so love now."
android:gravity="center"
android:textSize="30dp"
android:textColor="#fff"
/>
For me it's working with a "mysql5"
sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
As suggested by this answer:
[link](url){:target="_blank"}
Works for jekyll or more specifically kramdown, which is a superset of markdown, as part of Jekyll's (default) configuration. But not for plain markdown. ^_^
I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.
First use z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.
Dealing with a very lightweight embedded version of busybox on Linux means many of the traditional commands are not available (bc, printf, dc, perl, python)
echo $((0x2f))
47
hexNum=2f
echo $((0x${hexNum}))
47
Credit to Peter Leung for this solution.
DELETE is for deleting the request resource:
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully …
PUT is for putting or updating a resource on the server:
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI …
For the full specification visit:
Since current browsers unfortunately do not support any other verbs than POST and GET in HTML forms, you usually cannot utilize HTTP to it's full extent with them (you can still hijack their submission via JavaScript though). The absence of support for these methods in HTML forms led to URIs containing verbs, like for instance
POST http://example.com/order/1/delete
or even worse
POST http://example.com/deleteOrder/id/1
effectively tunneling CRUD semantics over HTTP. But verbs were never meant to be part of the URI. Instead HTTP already provides the mechanism and semantics to CRUD a Resource (e.g. an order) through the HTTP methods. HTTP is a protocol and not just some data tunneling service.
So to delete a Resource on the webserver, you'd call
DELETE http://example.com/order/1
and to update it you'd call
PUT http://example.com/order/1
and provide the updated Resource Representation in the PUT body for the webserver to apply then.
So, if you are building some sort of client for a REST API, you will likely make it send PUT and DELETE requests. This could be a client built inside a browser, e.g. sending requests via JavaScript or it could be some tool running on a server, etc.
For some more details visit:
char *a = new char[10];
My question is that how can I get the length of a char *
It is very simply.:) It is enough to add only one statement
size_t N = 10;
char *a = new char[N];
Now you can get the size of the allocated array
std::cout << "The size is " << N << std::endl;
Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.
The difference is the following. if to take your code snippet as an example
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
then std::strlen( a ) will return 5 instead of 6 as in your code.
So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string
. It has methof size and its synonym length that allows to get the size of the array at any time.
For example
std::string s( "aaaaa" );
std::cout << s.length() << std::endl;
or
std::string s;
s.resize( 10 );
std::cout << s.length() << std::endl;
On MySQL.com, MD5s are listed alongside each file that you can download. For instance, MySQL "Windows Essentials" 5.1 is 528c89c37b3a6f0bd34480000a56c372.
You can download md5 (md5.exe), a command line tool that will calculate the MD5 of any file that you have locally. MD5 is just like any other cryptographic hash function, which means that a given array of bytes will always produce the same hash. That means if your downloaded MySQL zip file (or whatever) has the same MD5 as they post on their site, you have the exact same file.
My favourite of the below is var_dump
, which when called as:
var_dump("%d", count);
produces output like:
patch.c:150:main(): count = 0
Credit to @"Jonathan Leffler". All are C89-happy:
Code
#define DEBUG 1
#include <stdarg.h>
#include <stdio.h>
void debug_vprintf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
/* Call as: (DOUBLE PARENTHESES ARE MANDATORY) */
/* var_debug(("outfd = %d, somefailed = %d\n", outfd, somefailed)); */
#define var_debug(x) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
__FILE__, __LINE__, __func__); debug_vprintf x; }} while (0)
/* var_dump("%s" variable_name); */
#define var_dump(fmt, var) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
__FILE__, __LINE__, __func__); debug_vprintf ("%s = " fmt, #var, var); }} while (0)
#define DEBUG_HERE do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): HERE\n", \
__FILE__, __LINE__, __func__); }} while (0)
Might be a problem with date configuration on server side or on client side. I've found this to be a common problem on multiple databases when the host is configured in spanish, french or whatever... that could affect the format dd/mm/yyyy or mm/dd/yyyy.
The solution is the /Y
switch:
xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y
If using another library is an option, the following may be easier:
package for_so;
import java.io.File;
import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;
public class Q7704827_SimpleRead
{
public static void
main(String[] args)
{
String fileName = args[0];
TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
String recipient = emailNode.nextTextFieldE("recipient");
String sender = emailNode.nextTextFieldE("sender");
String subject = emailNode.nextTextFieldE("subject");
String description = emailNode.nextTextFieldE("description");
emailNode.verifyNoMoreChildren();
System.out.println("recipient = " + recipient);
System.out.println("sender = " + sender);
System.out.println("subject = " + subject);
System.out.println("desciption = " + description);
}
}
The library and its documentation are at rasmustorkel.com
Yes, this is frequently called a multimap
.
May the div with id="content" not be created when this event is attached? You can try live() jquery method.
Else there may be multiple divs with the same id or you just spelled it wrong, it happens...
Editing the path of the keystore file solved my problem.
If you are branch master
and you do a git checkout <SHA>
I'm fairly certain that this causes git to load that commit in a detached state, changing you out of the current branch.
If you want to make changes you can and then you can do a git checkout -b <mynewbranch>
to create a new branch based off that commit and any changes you have made.
You simply don't call the function.
>>>def x():
>>> print(20)
>>>y = x
>>>y()
20
The brackets tell python that you are calling the function, so when you put them there, it calls the function and assigns y
the value returned by x
(which in this case is None
).
You can try this ! This should work on windows machines.
for /F "usebackq tokens=1,2,3 delims=-" %%I IN (`echo %date%`) do echo "%%I" "%%J" "%%K"
Edit: please see my other answer, as you probably don't need this now.
As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".
This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:
@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);
@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);
Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild
Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.
So, now you could set the onCompletion listener of the MediaPlayer instance like this:
OnCompletionListener ocl = new OnCompletionListener()
{
@Override
public void onCompletion(MediaPlayer mp)
{
// Do stuff
}
};
Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);
The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.
after you build your image do the following:
docker tag <image id> mynewtag:version
after that you will see your image is no longer named <none>
when you go docker images
.
Be sure to include the $route service into your scope and do this:
$route.reload();
See this:
Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.
Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.
Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.
I see a bunch of answers that say putting everything about user 123 at resource "/user/123" is RESTful.
Roy Fielding, who coined the term, says REST APIs must be hypertext-driven. In particular, "A REST API must not define fixed resource names or hierarchies".
So if your "/user/123" path is hardcoded on the client, it's not really RESTful. A good use of HTTP, maybe, maybe not. But not RESTful. It has to come from hypertext.
adding this worked for me:
<link href="https://fortawesome.github.io/Font-Awesome/assets/font-awesome/css/font-awesome.css" rel="stylesheet">
so full example is:
<link href="https://github.com/FortAwesome/Font-Awesome/blob/master/web-fonts-with-css/css/fontawesome.css" rel="stylesheet">_x000D_
<a class="btn-cta-freequote" href="#">Compute <i class="fa fa-calculator"></i></a>
_x000D_
import pickle
your_data = {'foo': 'bar'}
# Store data (serialize)
with open('filename.pickle', 'wb') as handle:
pickle.dump(your_data, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Load data (deserialize)
with open('filename.pickle', 'rb') as handle:
unserialized_data = pickle.load(handle)
print(your_data == unserialized_data)
The advantage of HIGHEST_PROTOCOL
is that files get smaller. This makes unpickling sometimes much faster.
Important notice: The maximum file size of pickle is about 2GB.
import mpu
your_data = {'foo': 'bar'}
mpu.io.write('filename.pickle', data)
unserialized_data = mpu.io.read('filename.pickle')
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
ForEach
Loop processes each ZIP file located within the $filepath
variable
foreach($file in $filepath)
{
$zip = $shell.NameSpace($file.FullName)
foreach($item in $zip.items())
{
$shell.Namespace($file.DirectoryName).copyhere($item)
}
Remove-Item $file.FullName
}
I don't know of a better way than:
unsigned char byData[xxx];
int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
sprintf(pBuffer[2 * i], "%02X", byData[i]);
}
You can speed it up by using a Nibble to Hex method
unsigned char byData[xxx];
const char szNibbleToHex = { "0123456789ABCDEF" };
int nLength = sizeof(byData) * 2;
char *pBuffer = new char[nLength + 1];
pBuffer[nLength] = 0;
for (int i = 0; i < sizeof(byData); i++)
{
// divide by 16
int nNibble = byData[i] >> 4;
pBuffer[2 * i] = pszNibbleToHex[nNibble];
nNibble = byData[i] & 0x0F;
pBuffer[2 * i + 1] = pszNibbleToHex[nNibble];
}
For users of IntelliJ IDEA or Android Studio make these steps:
* From the menu Build/Generate signed APK
* You need to create a keystore path. From the dialog click Create new
. You will create a jks file that includes your keys. Select folder, define a password. So your keystore ok.
* Create new key by for your application by using alias, key password, your name etc.
* Click next.
* From the dialog either select Proguard or not.
Your signed APK file is ready.
Help file: https://www.jetbrains.com/idea/webhelp/generate-signed-apk-wizard.html
To do it on page load:
window.onload = function () {_x000D_
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();_x000D_
}
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
I had the problem with it being in a data set being pushed across the wire (webservice to client) that it would automatically change because the DataColumn's DateType field was set to local. Make sure you check what the DateType is if your pushing DataSets across.
If you don't want it to change, set it to Unspecified
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
You don't import methods in Java, only types:
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
The exception is so-called "static imports", which let you import class (static
) methods from other types.
There was recently a node module that was made that solves this problem so you don't have to create another component.
https://github.com/Ajackster/react-native-global-props
https://www.npmjs.com/package/react-native-global-props
The documentation states that in your highest order component, import the setCustomText
function like so.
import { setCustomText } from 'react-native-global-props';
Then, create the custom styling/props you want for the react-native Text
component. In your case, you'd like fontFamily to work on every Text
component.
const customTextProps = {
style: {
fontFamily: yourFont
}
}
Call the setCustomText
function and pass your props/styles into the function.
setCustomText(customTextProps);
And then all react-native Text
components will have your declared fontFamily along with any other props/styles you provide.
#!/usr/bin/python
import serial, time
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
#ser.port = "/dev/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
ser.bytesize = serial.EIGHTBITS #number of bits per bytes
ser.parity = serial.PARITY_NONE #set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE #number of stop bits
#ser.timeout = None #block read
ser.timeout = 1 #non-block read
#ser.timeout = 2 #timeout block read
ser.xonxoff = False #disable software flow control
ser.rtscts = False #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 #timeout for write
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output
#and discard all that is in buffer
#write data
ser.write("AT+CSQ")
print("write data: AT+CSQ")
time.sleep(0.5) #give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
Just code-golfing Rebecca Chernoff's solution :-)
alert(("This is a string.".match(/is/g) || []).length);
For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the
while(!condition)
the code will be:
int x = people;
int counter = 0;
while(x != counter)
{
counter++;
}
return 0;
PreparedStatement
alone does not help you if you are still concatenating Strings.
For instance, one rogue attacker can still do the following:
Not only SQL, but even JPQL or HQL can be compromised if you are not using bind parameters.
Bottom line, you should never use string concatenation when building SQL statements. Use a dedicated API for that purpose, like JPA Criteria API.
I know this is a fairly old question, but I was searching for a solution to generically deserialize nested JSON to a Map<String, Object>
, and found nothing.
The way my yaml deserializer works, it defaults JSON objects to Map<String, Object>
when you don't specify a type, but gson doesn't seem to do this. Luckily you can accomplish it with a custom deserializer.
I used the following deserializer to naturally deserialize anything, defaulting JsonObject
s to Map<String, Object>
and JsonArray
s to Object[]
s, where all the children are similarly deserialized.
private static class NaturalDeserializer implements JsonDeserializer<Object> {
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) {
if(json.isJsonNull()) return null;
else if(json.isJsonPrimitive()) return handlePrimitive(json.getAsJsonPrimitive());
else if(json.isJsonArray()) return handleArray(json.getAsJsonArray(), context);
else return handleObject(json.getAsJsonObject(), context);
}
private Object handlePrimitive(JsonPrimitive json) {
if(json.isBoolean())
return json.getAsBoolean();
else if(json.isString())
return json.getAsString();
else {
BigDecimal bigDec = json.getAsBigDecimal();
// Find out if it is an int type
try {
bigDec.toBigIntegerExact();
try { return bigDec.intValueExact(); }
catch(ArithmeticException e) {}
return bigDec.longValue();
} catch(ArithmeticException e) {}
// Just return it as a double
return bigDec.doubleValue();
}
}
private Object handleArray(JsonArray json, JsonDeserializationContext context) {
Object[] array = new Object[json.size()];
for(int i = 0; i < array.length; i++)
array[i] = context.deserialize(json.get(i), Object.class);
return array;
}
private Object handleObject(JsonObject json, JsonDeserializationContext context) {
Map<String, Object> map = new HashMap<String, Object>();
for(Map.Entry<String, JsonElement> entry : json.entrySet())
map.put(entry.getKey(), context.deserialize(entry.getValue(), Object.class));
return map;
}
}
The messiness inside the handlePrimitive
method is for making sure you only ever get a Double or an Integer or a Long, and probably could be better, or at least simplified if you're okay with getting BigDecimals, which I believe is the default.
You can register this adapter like:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
And then call it like:
Object natural = gson.fromJson(source, Object.class);
I'm not sure why this is not the default behavior in gson, since it is in most other semi-structured serialization libraries...
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)
Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.
When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.
PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).
When using Webpack you need to require
images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} />
you need to use <img src={require('/images/image-name.png')} />
replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img.
const optionNodes = Array.from(selectNode.children);
const comparator = new Intl.Collator(lang.slice(0, 2)).compare;
optionNodes.sort((a, b) => comparator(a.textContent, b.textContent));
optionNodes.forEach((option) => selectNode.appendChild(option));
My use case was to localize a country select dropdown with locale aware sorting. This was used on 250 + options and was very performant ~10ms on my machine.
This can be confusing for anyone using nodejs for the first time. It is actually possible to pipe your node console output to the browser console. Take a look at connect-browser-logger on github
UPDATE: As pointed out by Yan, connect-browser-logger appears to be defunct. I would recommend NodeMonkey as detailed here : Output to Chrome console from Node.js
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int[] numbers=new int[5];
String x=null;
System.out.print("enter the number 10:"+"/n");
for(int i=0;i<5;i++){
numbers[i] = input.nextInt();
}
System.out.print("Numbers : count"+"\n");
int count=1;
Arrays.sort(numbers);
for(int z=0;z<5;z++){
for(int j=0;j<z;j++){
if(numbers[z]==numbers[j] & j!=z){
count=count+1;
}
}
System.out.print(numbers[z]+" - "+count+"\n");
count=1;
}
You try to set the height
property of an inline
element, which is not possible. You can try to make it a block
element, or perhaps you meant to alter the line-height
property?
Short answer:
// lib.js
module.exports.your_function = function () {
// Something...
};
// app.js
require('./lib.js').your_function();
First method you can try this
$department->department_name = $request->department_name;
$department->status = $request->status;
$department->save();
Another way to insert records into the database with create function
$department = new Department;
// Another Way to insert records
$department->create($request->all());
return redirect('admin/departments');
You need to set the filledby in Department model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $fillable = ['department_name','status'];
}
As of PHP 7.1,
catch( AError | BError $e )
{
handler1( $e )
}
interestingly, you can also:
catch( AError | BError $e )
{
handler1( $e )
} catch (CError $e){
handler2($e);
} catch(Exception $e){
handler3($e);
}
and in earlier versions of PHP:
catch(Exception $ex){
if($ex instanceof AError){
//handle a AError
} elseif($ex instanceof BError){
//handle a BError
} else {
throw $ex;//an unknown exception occured, throw it further
}
}
Try something like this
public static TestEnum GetMyEnum(this string title)
{
EnumBookType st;
Enum.TryParse(title, out st);
return st;
}
So you can do
TestEnum en = "Value1".GetMyEnum();
Also instead of adding each file manually, we could do something like:
git add --all
OR
git add -A
This will also remove any files not present or deleted (Tracked files in the current working directory which are now absent).
If you only want to add files which are tracked and have changed, you would want to do
git add -u
According to the specifications of the World Wide Web Consortium (w3C), there are 5 characters that must not appear in their literal form in an XML document, except when used as markup delimiters or within a comment, a processing instruction, or a CDATA section. In all the other cases, these characters must be replaced either using the corresponding entity or the numeric reference according to the following table:
Original CharacterXML entity replacementXML numeric replacement
< < <
> > >
" " "
& & &
' ' '
Notice that the aforementioned entities can be used also in HTML, with the exception of ', that was introduced with XHTML 1.0 and is not declared in HTML 4. For this reason, and to ensure retro-compatibility, the XHTML specification recommends the use of ' instead.
if(A == "haha" && B == "hihi") {
//hahahihi?
}
if(A == "haha" || B != "hihi") {
//hahahihi!?
}
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
white-space: nowrap;
: Will never break text, will keep other defaults
white-space: pre;
: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)
You can disable any Python warnings via the PYTHONWARNINGS
environment variable. In this case, you want:
export PYTHONWARNINGS="ignore:Unverified HTTPS request"
To disable using Python code (requests >= 2.16.0
):
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
For requests < 2.16.0
, see original answer below.
Original answer
The reason doing urllib3.disable_warnings()
didn't work for you is because it looks like you're using a separate instance of urllib3 vendored inside of requests.
I gather this based on the path here: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py
To disable warnings in requests' vendored urllib3, you'll need to import that specific instance of the module:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
You could use a CURSOR in this case:
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
FETCH NEXT
FROM @getid INTO @id, @name
END
CLOSE @getid
DEALLOCATE @getid
Modified to show multiple parameters from the table.
From a little search, that I understand the file should be opened in universal newline mode, which you cannot directly do with a response content (I guess).
To finish the task, you can either save the downloaded content to a temporary file, or process it in memory.
Save as file:
import requests
import csv
import os
temp_file_name = 'temp_csv.csv'
url = 'http://url.to/file.csv'
download = requests.get(url)
with open(temp_file_name, 'w') as temp_file:
temp_file.writelines(download.content)
with open(temp_file_name, 'rU') as temp_file:
csv_reader = csv.reader(temp_file, dialect=csv.excel_tab)
for line in csv_reader:
print line
# delete the temp file after process
os.remove(temp_file_name)
In memory:
(To be updated)
If you want to run all the tests from various test case classes and you're happy to specify them explicitly then you can do it like this:
from unittest import TestLoader, TextTestRunner, TestSuite
from uclid.test.test_symbols import TestSymbols
from uclid.test.test_patterns import TestPatterns
if __name__ == "__main__":
loader = TestLoader()
tests = [
loader.loadTestsFromTestCase(test)
for test in (TestSymbols, TestPatterns)
]
suite = TestSuite(tests)
runner = TextTestRunner(verbosity=2)
runner.run(suite)
where uclid
is my project and TestSymbols
and TestPatterns
are subclasses of TestCase
.
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.
To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.
Here is how to do it:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:
<profile>
<id>runSonar</id>
<activation>
<property>
<name>runSonar</name>
<value>true</value>
</property>
</activation>
<properties>
<sonar.language>java</sonar.language>
<sonar.host.url>http://sonar.url</sonar.host.url>
<sonar.login>tokenX</sonar.login>
<sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
<sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
<jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>default-prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<append>true</append>
<destFile>${jacoco.destFile}</destFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.2</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar
you get the complete coverage.
The magic here is maven.multiModuleProjectDirectory
. This folder is always the folder where you started your maven build.
After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.
# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]
# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]
# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...
Requirements:
To remove the association between the local and remote branch run:
git config --unset branch.<local-branch-name>.remote
git config --unset branch.<local-branch-name>.merge
Optionally delete the local branch afterwards if you don't need it:
git branch -d <branch>
This won't delete the remote branch.
You can also make a function in Bash, add it to .bashrc
or something and then use it wherever you want.
change-ext() {
for file in *.$1; do mv "$file" "$(basename "$file" .$1).$2"; done
}
Usage:
change-ext css scss
Source of code in function: https://stackoverflow.com/a/1224786/6732111
Cellspacing is all around the cell and cannot be changed (i.e. if it's set to one, there will be 1 pixel of space on all sides). Padding can be specified discreetly (e.g. padding-top
, padding-bottom
, padding-left
, and padding-right;
or padding: [top] [right] [bottom] [left];
).
I am not aware of any pure shell XML parsing tool. So you will most likely need a tool written in an other language.
My XML::Twig Perl module comes with such a tool: xml_grep
, where you would probably write what you want as xml_grep -t '/html/head/title' xhtmlfile.xhtml > titleOfXHTMLPage.txt
(the -t
option gives you the result as text instead of xml)
If you are updating to v28
change the compileSdkVersion to compileSdkVersion 28
Try to import
java.util.List;
instead of
java.awt.List;
Try
List<SubProduct> subProducts = new List<SubProduct>(Model.subproduct);
or
List<SubProduct> subProducts = Model.subproducts as List<SubProduct>;
I've added a number of helper methods to the O2 Platform (Open Source project) which allow you easily script an interaction with another process via the console output and input (see http://code.google.com/p/o2platform/source/browse/trunk/O2_Scripts/APIs/Windows/CmdExe/CmdExeAPI.cs)
Also useful for you might be the API that allows the viewing of the console output of the current process (in an existing control or popup window). See this blog post for more details: http://o2platform.wordpress.com/2011/11/26/api_consoleout-cs-inprocess-capture-of-the-console-output/ (this blog also contains details of how to consume the console output of new processes)
Would the following Macro help you?
Sub activateSheet(sheetname As String)
'activates sheet of specific name
Worksheets(sheetname).Activate
End Sub
Basically you want to make use of the .Activate function. Or you can use the .Select function like so:
Sub activateSheet(sheetname As String)
'selects sheet of specific name
Sheets(sheetname).Select
End Sub
Using the Safari browser (not Chrome, Firefox or Opera) on Mac OS X 10.9 (Mavericks) visit https://registry.npmjs.org
Click the Show certificate button and then check the checkbox labelled Always trust. Then click Continue and enter your password if required.
Curl should now work with that URL correctly.
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
When none of the if
test in number_translator()
evaluate to true, the function returns None
. The error message is the consequence of that.
Whenever you see an error that include 'NoneType'
that means that you have an operand or an object that is None
when you were expecting something else.
I just created a local connection by breaking my head for hours. So thought of helping you guys.
Step 1: Check your file name listener.ora located at
C:\app\\product\12.1.0\dbhome_3\NETWORK\ADMIN
Check your HOSTNAME, PORT AND SERVICE and give the same while creating new database connection.
Step 2: if this doesnt work, try these combinations give PORT:1521
and SID: orcl
give PORT: and
SID: orcl
give PORT:1521
and SID: pdborcl
give PORT:1521
and
SID: admin
If you get the error as "wrong username and password" :
Make sure you are giving correct username and password
if still it doesnt work try this: Username :system Password: .
Hope it helps!!!!
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
As Jean mentioned, using a StringBuilder
instead of +=
would be better. But if you're looking for something simpler, Guava, IOUtils, and Jsoup are all good options.
Example with Guava:
String content = Files.asCharSource(new File("/path/to/mypage.html"), StandardCharsets.UTF_8).read();
Example with IOUtils:
InputStream in = new URL("/path/to/mypage.html").openStream();
String content;
try {
content = IOUtils.toString(in, StandardCharsets.UTF_8);
} finally {
IOUtils.closeQuietly(in);
}
Example with Jsoup:
String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").toString();
or
String content = Jsoup.parse(new File("/path/to/mypage.html"), "UTF-8").outerHtml();
NOTES:
Files.readLines()
andFiles.toString()
These are now deprecated as of Guava release version 22.0 (May 22, 2017).
Files.asCharSource()
should be used instead as seen in the example above. (version 22.0 release diffs)
IOUtils.toString(InputStream)
andCharsets.UTF_8
Deprecated as of Apache Commons-IO version 2.5 (May 6, 2016). IOUtils.toString
should now be passed the InputStream
and the Charset
as seen in the example above. Java 7's StandardCharsets
should be used instead of Charsets
as seen in the example above. (deprecated Charsets.UTF_8)
You could also create your own conversion function, inside which you can use exception blocks:
CREATE OR REPLACE FUNCTION convert_to_integer(v_input text)
RETURNS INTEGER AS $$
DECLARE v_int_value INTEGER DEFAULT NULL;
BEGIN
BEGIN
v_int_value := v_input::INTEGER;
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Invalid integer value: "%". Returning NULL.', v_input;
RETURN NULL;
END;
RETURN v_int_value;
END;
$$ LANGUAGE plpgsql;
Testing:
=# select convert_to_integer('1234');
convert_to_integer
--------------------
1234
(1 row)
=# select convert_to_integer('');
NOTICE: Invalid integer value: "". Returning NULL.
convert_to_integer
--------------------
(1 row)
=# select convert_to_integer('chicken');
NOTICE: Invalid integer value: "chicken". Returning NULL.
convert_to_integer
--------------------
(1 row)
I've faced the same issue, this is because I am pushing my code directly in the master branch, and I don't have rights for this. So I push my code in a new branch and after that, I created a pull request to merge with master.
A little plus:
version = RN 0.57.7
secureTextEntry={true}
does not work when the keyboardType
was "phone-pad"
or "email-address"
The simplest short form to me is something like:
#find web forms in my project except in compilation directories
(gci -recurse -path *.aspx,*.ascx).fullname -inotmatch '\\obj\\|\\bin\\'
And if you need more complex logic then use a filter:
filter Filter-DirectoryBySomeLogic{
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
$fsObject,
[switch]$exclude
)
if($fsObject -is [System.IO.DirectoryInfo])
{
$additional_logic = $true ### replace additional logic here
if($additional_logic){
if(!$exclude){ return $fsObject }
}
elseif($exclude){ return $fsObject }
}
}
gci -Directory -Recurse | Filter-DirectoryBySomeLogic | ....
Apparently it does not and I didn't quite expect it would. HOWEVER Ivan brings up a good possibility that has escaped Android people.
What is the purpose of an emulator? to EMULATE, right? I don't see why for testing purposes -provided the tester understands the limitations- the emulator might not add a Wifi emulator.
It could for example emulate WiFi access by using the underlying internet connection of the host. Obviously testing WPA/WEP differencess would not make sense but at least it could toggle access via WiFi.
Or some sort of emulator plugin where there would be a base WiFi emulator that would emulate WiFi access via the underlying connection but then via configuration it could emulate WPA/WEP by providing a list of fake WiFi networks and their corresponding fake passwords that would be matched against a configurable list of credentials.
After all the idea is to do initial testing on the emulator and then move on to the actual device.
You might also consider using the Android platform's way of persisting data across orientation changes: onRetainNonConfigurationInstance()
and getLastNonConfigurationInstance()
.
This allows you to persist data across configuration changes, such as information you may have gotten from a server fetch or something else that's been computed in onCreate
or since, while also allowing Android to re-layout your Activity
using the xml file for the orientation now in use.
It should be noted that these methods are now deprecated (although still more flexible than handling orientation change yourself as most of the above solutions suggest) with the recommendation that everyone switch to Fragments
and instead use setRetainInstance(true)
on each Fragment
you want to retain.
You could also use forEach
on the FormData
object directly:
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var json = JSON.stringify(object);
And for those who prefer the same solution with ES6 arrow functions:
var object = {};
formData.forEach((value, key) => object[key] = value);
var json = JSON.stringify(object);
And for those who want support for multi select lists or other form elements with multiple values (since there are so many comments below the answer regarding this issue I will add a possible solution):
var object = {};
formData.forEach((value, key) => {
// Reflect.has in favor of: object.hasOwnProperty(key)
if(!Reflect.has(object, key)){
object[key] = value;
return;
}
if(!Array.isArray(object[key])){
object[key] = [object[key]];
}
object[key].push(value);
});
var json = JSON.stringify(object);
Here a Fiddle demonstrating the use of this method with a simple multi select list.
As a side note for those ending up here, in case the purpose of converting the form data to json is to send it through a XML HTTP request to a server you can send the FormData
object directly without converting it. As simple as this:
var request = new XMLHttpRequest();
request.open("POST", "http://example.com/submitform.php");
request.send(formData);
See also Using FormData Objects on MDN for reference:
As mentioned in one of the comments below my answer the JSON stringify
method won't work out of the box for all types of objects. For more information on what types are supported I would like to refer to the Description section in the MDN documentation of JSON.stringify
.
In the description is also mentioned that:
If the value has a toJSON() method, it's responsible to define what data will be serialized.
This means that you can supply your own toJSON
serialization method with logic for serializing your custom objects. Like that you can quickly and easily build serialization support for more complex object trees.
what are you exactly want check for login or user ? a login is created on server level and a user is created at database level so a login is unique in server
also a user is created against a login, a user without login is an orphaned user and is not useful as u cant carry out sql server login without a login
maybe u need this
check for login
select 'X' from master.dbo.syslogins where loginname=<username>
the above query return 'X' if login exists else return null
then create a login
CREATE LOGIN <username> with PASSWORD=<password>
this creates a login in sql server .but it accepts only strong passwords
create a user in each database you want to for login as
CREATE USER <username> for login <username>
assign execute rights to user
GRANT EXECUTE TO <username>
YOU MUST HAVE SYSADMIN permissions or say 'sa' for short
you can write a sql procedure for that on a database
create proc createuser
(
@username varchar(50),
@password varchar(50)
)
as
begin
if not exists(select 'X' from master.dbo.syslogins where loginname=@username)
begin
if not exists(select 'X' from sysusers where name=@username)
begin
exec('CREATE LOGIN '+@username+' WITH PASSWORD='''+@password+'''')
exec('CREATE USER '+@username+' FOR LOGIN '+@username)
exec('GRANT EXECUTE TO '+@username)
end
end
end
i++ is known as Post Increment whereas ++i is called Pre Increment.
i++
i++
is post increment because it increments i
's value by 1 after the operation is over.
Lets see the following example:
int i = 1, j;
j = i++;
Here value of j = 1
but i = 2
. Here value of i
will be assigned to j
first then i
will be incremented.
++i
++i
is pre increment because it increments i
's value by 1 before the operation.
It means j = i;
will execute after i++
.
Lets see the following example:
int i = 1, j;
j = ++i;
Here value of j = 2
but i = 2
. Here value of i
will be assigned to j
after the i
incremention of i
.
Similarly ++i
will be executed before j=i;
.
For your question which should be used in the incrementation block of a for loop? the answer is, you can use any one.. doesn't matter. It will execute your for loop same no. of times.
for(i=0; i<5; i++)
printf("%d ",i);
And
for(i=0; i<5; ++i)
printf("%d ",i);
Both the loops will produce same output. ie 0 1 2 3 4
.
It only matters where you are using it.
for(i = 0; i<5;)
printf("%d ",++i);
In this case output will be 1 2 3 4 5
.
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [(
brackets which wrap the variable.
From python >= 3.5 onward, you can use **
, glob.iglob(path/**, recursive=True)
and it seems the most pythonic solution, i.e.:
import glob, os
for filename in glob.iglob('/pardadox-music/**', recursive=True):
if os.path.isfile(filename): # filter dirs
print(filename)
Output:
/pardadox-music/modules/her1.mod
/pardadox-music/modules/her2.mod
...
Notes:
1 - glob.iglob
glob.iglob(pathname, recursive=False)
Return an iterator which yields the same values as
glob()
without actually storing them all simultaneously.
2 - If recursive is True
, the pattern '**'
will match any files and
zero or more directories
and subdirectories
.
3 - If the directory contains files starting with .
they won’t be matched by default. For example, consider a directory containing card.gif
and .card.gif
:
>>> import glob
>>> glob.glob('*.gif') ['card.gif']
>>> glob.glob('.c*')['.card.gif']
4 - You can also use rglob(pattern)
,
which is the same as calling glob()
with **/
added in front of the given relative pattern.
If you want to avoid encode html entities more than once
function encodeHTML(str){
return str.replace(/([\u00A0-\u9999<>&])(.|$)/g, function(full, char, next) {
if(char !== '&' || next !== '#'){
if(/[\u00A0-\u9999<>&]/.test(next))
next = '&#' + next.charCodeAt(0) + ';';
return '&#' + char.charCodeAt(0) + ';' + next;
}
return full;
});
}
function decodeHTML(str){
return str.replace(/&#([0-9]+);/g, function(full, int) {
return String.fromCharCode(parseInt(int));
});
}
# Example
var text = "<a>Content © <#>&<&#># </a>";
text = encodeHTML(text);
console.log("Encode 1 times: " + text);
// <a>Content © <#>&<&#># </a>
text = encodeHTML(text);
console.log("Encode 2 times: " + text);
// <a>Content © <#>&<&#># </a>
text = decodeHTML(text);
console.log("Decoded: " + text);
// <a>Content © <#>&<&#># </a>
In my case this error occurred with dot net core and Microsoft.Data.SqlClient
.
The solution was to add ;TrustServerCertificate=true
to the end of the connection string.
Like others have mentioned, you probably want to look at reusing an existing graphing solution, but rotating text isn't too difficult. The somewhat confusing bit (to me) is that you rotate the whole context and then draw on it:
ctx.rotate(Math.PI*2/(i*6));
The angle is in radians. The code is taken from this example, which I believe was made for the transformations part of the MDC canvas tutorial.
Please see the answer below for a more complete solution.
Literals that start with 0x
are hexadecimal integers. (base 16)
The number 0x6400
is 25600
.
6 * 16^3 + 4 * 16^2 = 25600
For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)
The number 0x6BF0
is 27632
.
6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576 + 2816 + 240 = 27632
If what you want is to hide the navigation bar completely in the controller, a much cleaner solution is to, in the root controller, have something like:
@implementation MainViewController
- (void)viewDidLoad {
self.navigationController.navigationBarHidden=YES;
//...extra code on view load
}
When you push a child view in the controller, the Navigation Bar will remain hidden; if you want to display it just in the child, you'll add the code for displaying it(self.navigationController.navigationBarHidden=NO;)
in the viewWillAppear
callback, and similarly the code for hiding it on viewWillDisappear
I'm currently working on a file like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/css" href="style.css" ?>
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width="100%"
height="100%"
viewBox="0 0 600 600">
...
And I tried to put this into style.css
:
svg {
background: #bf1f1f;
}
It's working on Chromium and Firefox, but I don't think that it's a good practice. EyeOfGnome image viewer doesn't render it, and Inkscape uses a special namespace to store such a background:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
version="1.1"
...
<sodipodi:namedview
pagecolor="#480000" ... >
Well, it seems that SVG root element is not part of paintable elements in SVG recommandations.
So I'd suggest to use the "rect" solution provided by Robert Longson because I guess that it is not a simple "hack". It seems to be the standard way to set a background with SVG.
Make sure, following jar file included in your class path and lib folder.
spring-core-3.0.5.RELEASE.jar
if you are using maven, make sure you have included dependency for spring-core-3xxxxx.jar file
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
Note : Replace ${org.springframework.version} with version number.
In my case, two leading '\\' working fine for me.
For example : if your word contains the '#' character (e.g. aa#100, you can escape it with two leading '\\'
key= aa\\#100
_x000D_
On codeplex was released new XNA Extension for Visual Studio 2012/2013. You can download it from: https://msxna.codeplex.com/releases
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
In Typescript and ES6 you can also use for..of:
for (var product of products) {
console.log(product.product_desc)
}
which will be transcoded to javascript:
for (var _i = 0, products_1 = products; _i < products_1.length; _i++) {
var product = products_1[_i];
console.log(product.product_desc);
}
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
The get
method of a dict (like for example characters
) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError
it returns the default value (if you call .get
with just one argument, the key, the default value is None
).
So an equivalent Python function (where calling myget(d, k, v)
is just like d.get(k, v)
might be:
def myget(d, k, v=None):
try: return d[k]
except KeyError: return v
The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get
returns it (so it's just incremented by one), else get
returns 0 (so the incrementing correctly gives 1
at a character's first occurrence in the string).
One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.
For instance :
$arr = array(
'a' => 123,
'b' => 456,
'c' => 789,
);
foreach ($arr as $key => $item) {
if ($item == 456) {
unset($arr[$key]);
}
}
var_dump($arr);
Will give you this array, in the end :
array
'a' => int 123
'c' => int 789
Which means that, in your case, something like this should do the trick :
foreach($images as $key => $image)
{
if($image == 'http://i27.tinypic.com/29yk345.gif' ||
$image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
$image == 'http://i42.tinypic.com/9pp2456x.gif')
{
unset($images[$key]);
}
}
By printing multiple values separated by a comma:
print "I have", card.price
The print statement will output each expression separated by spaces, followed by a newline.
If you need more complex formatting, use the ''.format()
method:
print "I have: {0.price}".format(card)
or by using the older and semi-deprecated %
string formatting operator.
You can send a prop from the parent and use it in child component so you will base child's state changes on the sent prop changes and you can handle this by using getDerivedStateFromProps in the child component.
Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
Maybe this url can help you: Activating Browser Modes with Doctype
Edit: Today we were able to override the compatibility view with:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
you may also want to look at that already answered question Differences in string compare methods in C#
You've got several options how to do this, either:
urlencode()
or rawurlencode()
- functions designed to encode URLs for http protocolstr_replace()
- "heavy machinery" string replacestrtr()
- would have better performance than str_replace()
when replacing multiple characterspreg_replace()
use regular expressions (perl compatible)strtr()
Assuming that you want to replace "\t"
and " "
with "%20"
:
$replace_pairs = array(
"\t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
You've got few options here, either replacing just space ~ ~
, again replacing space and tab ~[ \t]~
or all kinds of spaces ~\s~
:
return preg_replace( '~\s~', '%20', $text);
Or when you need to replace string like this "\t \t \t \t"
with just one %20
:
return preg_replace( '~\s+~', '%20', $text);
I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (
)
You can set the background color of an object using CSS.
You can also use JavaScript to attach click handlers to objects and they can change the style of an object using element.style.property = 'value';
. In the example below I've attached it in the HTML to a button but the handler could equally have been added to the body element or defined entirely in JavaScript.
body {_x000D_
background-color: blue;_x000D_
}
_x000D_
<button onclick="document.body.style.backgroundColor = 'green';">Green</button>
_x000D_
Check the link Regular Expression Demo
use the below reg exp
[a-z] + [^0-9\s.]+|.(?!\d)
For Microsoft Access
UPDATE TableA A
INNER JOIN TableB B
ON A.ID = B.ID
SET A.Name = B.Name
We now finally have IDENTITY
columns like many other databases, in case of which a sequence is auto-generated behind the scenes. This solution is much faster than a trigger-based one as can be seen in this blog post.
So, your table creation would look like this:
CREATE TABLE qname
(
qname_id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL PRIMARY KEY,
qname VARCHAR2(4000) NOT NULL -- CONSTRAINT qname_uk UNIQUE
);
According to the documentation, you cannot do that:
Restriction on Default Column Values A DEFAULT expression cannot contain references to PL/SQL functions or to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, PRIOR, and ROWNUM, or date constants that are not fully specified.
The standard way to have "auto increment" columns in Oracle is to use triggers, e.g.
CREATE OR REPLACE TRIGGER my_trigger
BEFORE INSERT
ON qname
FOR EACH ROW
-- Optionally restrict this trigger to fire only when really needed
WHEN (new.qname_id is null)
DECLARE
v_id qname.qname_id%TYPE;
BEGIN
-- Select a new value from the sequence into a local variable. As David
-- commented, this step is optional. You can directly select into :new.qname_id
SELECT qname_id_seq.nextval INTO v_id FROM DUAL;
-- :new references the record that you are about to insert into qname. Hence,
-- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
-- obtained from your sequence, before inserting
:new.qname_id := v_id;
END my_trigger;
Read more about Oracle TRIGGERs in the documentation
what is the difference between structure and union?
Short cut answer is: The deference is in memory allocation. Explanation: In structure, memory space will be created for all members inside structure. In union memory space will be created only for a member which needs largest memory space. Consider the following code:
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
Here there are two members inside struct and union: int and long int. Memory space for int is: 4 byte and Memory space for long int is: 8 in 32 bit operating system.
So for struct 4+8=12 bytes will be created while 8 bytes will be created for union
Code example:
#include<stdio.h>
struct s_tag
{
int a;
long int b;
} x;
union u_tag
{
int a;
long int b;
} y;
int main()
{
printf("Memory allocation for structure = %d", sizeof(x));
printf("\nMemory allocation for union = %d", sizeof(y));
return 0;
}
Ref:http://www.codingpractise.com/home/c-programming/structure-and-union/
There is an easy tool for timing. https://github.com/RalphMao/PyTimer
It can work like a decorator:
from pytimer import Timer
@Timer(average=False)
def matmul(a,b, times=100):
for i in range(times):
np.dot(a,b)
Output:
matmul:0.368434
matmul:2.839355
It can also work like a plug-in timer with namespace control(helpful if you are inserting it to a function which has a lot of codes and may be called anywhere else).
timer = Timer()
def any_function():
timer.start()
for i in range(10):
timer.reset()
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.checkpoint('block1')
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.checkpoint('block2')
np.dot(np.ones((100,1000)), np.zeros((1000,1000)))
for j in range(20):
np.dot(np.ones((100,1000)), np.zeros((1000,500)))
timer.summary()
for i in range(2):
any_function()
Output:
========Timing Summary of Default Timer========
block2:0.065062
block1:0.032529
========Timing Summary of Default Timer========
block2:0.065838
block1:0.032891
Hope it will help
1. In the loop you are assigning value rather than comparing value so
i=((Main.size())-1) -> i=(-1) since Main.size()
Main[i] will yield "Vector Subscript out of Range" coz i = -1.
2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.
I don't think I'm allowed to post the code, but the above post mentioning the WWDC sample code is correct. Here is the link: https://developer.apple.com/downloads/index.action?name=WWDC%202013
The file you're looking for is the category on UIImage, and the method is applyLightEffect.
As I noted above in a comment, the Apple Blur has saturation and other things going on besides blur. A simple blur will not do... if you are looking to emulate their style.
If a
is a prime then the while x:
in your code will run forever, since x
will remain True
.
So why is that while
there?
I think you wanted to end the for loop when you found a factor, but didn't know how, so you added that while since it has a condition. So here is how you do it:
def is_prime(a):
x = True
for i in range(2, a):
if a%i == 0:
x = False
break # ends the for loop
# no else block because it does nothing ...
if x:
print "prime"
else:
print "not prime"
I was facing this issue only while importing my own created components/services For those of you like me, for whom the accepted solution did not work, can try this:
Add
"baseUrl": "src"
in your tsconfig.json
. The reason is that visual code IDE is unable to resolve the base url so is unable to resolve path to imported components and gives error/warning.
Whereas angular compiler takes src
as baseurl by default so it is able to compile.
NOTE:
You need to restart VS Code IDE to make this change come into effect.
EDIT:
As mentioned in one of the comments, in some cases changing workspace version might also work. More details here: https://github.com/Microsoft/vscode/issues/34681#issuecomment-331306869
Access-Engine does not support
SELECT count(DISTINCT....) FROM ...
You have to do it like this:
SELECT count(*)
FROM
(SELECT DISTINCT Name FROM table1)
Its a little workaround... you're counting a DISTINCT selection.
Dll v/s Exe
1)DLL file is a dynamic link library which can be used in exe files and
other dll files.
EXE file is a executable file which runs in a separate
process which is managed by OS.
2)DLLs are not directly executable . They are separate files containing functions that can be called by programs and other DLLs to perform computations and functions.
An EXE is a program that can be executed . Ex :Windows program
3)Reusability
DLL: They can be reused for some other application. As long as the coder knows the names and parameters of the functions and procedures in the DLL file .
EXE: Only for specific purpose .
4)A DLL would share the same process and memory space of the calling application while an
EXE creates its separate process and memory space.
5)Uses
DLL: You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).
EXE: When we work with project templates like Windows Forms Applications, Console Applications, WPF Applications and Windows Services they generate an exe assembly when compiled.
6)Similarities :
Both DLL and EXE are binary files have a complex nested structure defined by the Portable Executable format, and they are not intended to be editable by users.
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
terminal 1
dd if=/dev/sda of=debian.img
terminal 2
killall -SIGUSR1 dd
go back to terminal 1
34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
Can I just install an NPM package that sits on the local filesystem, or perhaps even from git?
Yes you can! From the docs https://docs.npmjs.com/cli/install
A package is:
- a) a folder containing a program described by a package.json file
- b) a gzipped tarball containing (a)
- c) a url that resolves to (b)
- d) a
<name>@<version>
that is published on the registry with (c)- e) a
<name>@<tag>
that points to (d)- f) a
<name>
that has a "latest" tag satisfying (e)- g) a
<git remote url>
that resolves to (b)
Isn't npm brilliant?
This problem is due to pdb files or CodeContracts.
To resolve it:
Clean your output folder and rebuild the solution.
Re-Configure the CodeContracts or disable it for temporary build.
Suggest that you store the number as an extended alphanumeric made up of characters that you wish to accept and store it in a varchar(32) or something like that. Strip out all the spaces , dashes, etc. Put the FORMATTING of the phone number into a separate field (possibly gleaned from the locale preferences) If you wish to support extensions, you should add them in a separate field;
If you use the view only url the user is not propted to login to there google account.
https://docs.google.com/viewer?url=http://my.domain.com/yourPdfUrlHere.pdf
erickson's answer worked perfectly:
Here's the working code.
CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
List<String> list = new ArrayList<String>();
if( src != null ) {
URL jar = src.getLocation();
ZipInputStream zip = new ZipInputStream( jar.openStream());
ZipEntry ze = null;
while( ( ze = zip.getNextEntry() ) != null ) {
String entryName = ze.getName();
if( entryName.startsWith("images") && entryName.endsWith(".png") ) {
list.add( entryName );
}
}
}
webimages = list.toArray( new String[ list.size() ] );
And I have just modify my load method from this:
File[] webimages = ...
BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex].getName() ));
To this:
String [] webimages = ...
BufferedImage image = ImageIO.read(this.getClass().getResource(webimages[nextIndex]));
The MessageDigest
class can provide you with an instance of the MD5 digest.
When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes()
it will use the platform default. (Not all platforms use the same defaults)
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
If you have a lot of data take a look at the .update(byte[])
method which can be called repeatedly. Then call .digest()
to obtain the resulting hash.
This is another solution which I use:
public class CustomAnimator {
private static final String TAG = "com.example.CustomAnimator";
private static Stack<AnimationEntry> animation_stack = new Stack<>();
public static final int DIRECTION_LEFT = 1;
public static final int DIRECTION_RIGHT = -1;
public static final int DIRECTION_UP = 2;
public static final int DIRECTION_DOWN = -2;
static class AnimationEntry {
View in;
View out;
int direction;
long duration;
}
public static boolean hasHistory() {
return !animation_stack.empty();
}
public static void reversePrevious() {
if (!animation_stack.empty()) {
AnimationEntry entry = animation_stack.pop();
slide(entry.out, entry.in, -entry.direction, entry.duration, false);
}
}
public static void clearHistory() {
animation_stack.clear();
}
public static void slide(final View in, View out, final int direction, long duration) {
slide(in, out, direction, duration, true);
}
private static void slide(final View in, final View out, final int direction, final long duration, final boolean save) {
ViewGroup in_parent = (ViewGroup) in.getParent();
ViewGroup out_parent = (ViewGroup) out.getParent();
if (!in_parent.equals(out_parent)) {
return;
}
int parent_width = in_parent.getWidth();
int parent_height = in_parent.getHeight();
ObjectAnimator slide_out;
ObjectAnimator slide_in;
switch (direction) {
case DIRECTION_LEFT:
default:
slide_in = ObjectAnimator.ofFloat(in, "translationX", parent_width, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, -out.getWidth());
break;
case DIRECTION_RIGHT:
slide_in = ObjectAnimator.ofFloat(in, "translationX", -out.getWidth(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationX", 0, parent_width);
break;
case DIRECTION_UP:
slide_in = ObjectAnimator.ofFloat(in, "translationY", parent_height, 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, -out.getHeight());
break;
case DIRECTION_DOWN:
slide_in = ObjectAnimator.ofFloat(in, "translationY", -out.getHeight(), 0);
slide_out = ObjectAnimator.ofFloat(out, "translationY", 0, parent_height);
break;
}
AnimatorSet animations = new AnimatorSet();
animations.setDuration(duration);
animations.playTogether(slide_in, slide_out);
animations.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationCancel(Animator arg0) {
}
@Override
public void onAnimationEnd(Animator arg0) {
out.setVisibility(View.INVISIBLE);
if (save) {
AnimationEntry ae = new AnimationEntry();
ae.in = in;
ae.out = out;
ae.direction = direction;
ae.duration = duration;
animation_stack.push(ae);
}
}
@Override
public void onAnimationRepeat(Animator arg0) {
}
@Override
public void onAnimationStart(Animator arg0) {
in.setVisibility(View.VISIBLE);
}
});
animations.start();
}
}
The usage of class. Let's say you have two fragments (list and details fragments)as shown below
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ui_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="@+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<FrameLayout
android:id="@+id/details_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
</FrameLayout>
Usage
View details_container = findViewById(R.id.details_container);
View list_container = findViewById(R.id.list_container);
// You can select the direction left/right/up/down and the duration
CustomAnimator.slide(list_container, details_container,CustomAnimator.DIRECTION_LEFT, 400);
You can use the function CustomAnimator.reversePrevious();
to get the previous view when the user pressed back.
I did it like this:
var listOfRows = new List<DataRow>();
foreach (var row in resultTable.Rows.Cast<DataRow>())
{
var isEmpty = row.ItemArray.All(x => x == null || (x!= null && string.IsNullOrWhiteSpace(x.ToString())));
if (!isEmpty)
{
listOfRows.Add(row);
}
}
$(".field-group_name").each(function() {
console.log($(this).text());
});
For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.
However, if you had multiple rules like this:
#foo > ul > li > ul > li > a:nth-child(3n+1) {
color: red;
}
#foo > ul > li > ul > li > a:nth-child(3n+2) {
color: green;
}
#foo > ul > li > ul > li > a:nth-child(3n+3) {
color: blue;
}
You could condense them to one of the following:
/* Sass */
#foo > ul > li > ul > li
> a:nth-child(3n+1)
color: red
> a:nth-child(3n+2)
color: green
> a:nth-child(3n+3)
color: blue
/* SCSS */
#foo > ul > li > ul > li {
> a:nth-child(3n+1) { color: red; }
> a:nth-child(3n+2) { color: green; }
> a:nth-child(3n+3) { color: blue; }
}
You can set the connection to a variable then disconnect it when you are done:
var db = mongoose.connect('mongodb://localhost:27017/somedb');
// Do some stuff
db.disconnect();
To also handle floating point numbers:
(Older) JavaScript:
var arr = ["20.0","40.1","80.2","400.3"],
n = arr.length,
sum = 0;
while(n--)
sum += parseFloat(arr[n]) || 0;
ECMA 5.1/6:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
arr.forEach(function(num){sum+=parseFloat(num) || 0;});
ES6:
var sum = ["20.0","40.1","80.2","400.3"].reduce((pv,cv)=>{
return pv + (parseFloat(cv)||0);
},0);
The reduce() is available in older ECMAScript versions, the arrow function is what makes this ES6-specific.
I'm passing in 0 as the first pv
value, so I don't need parseFloat around it — it'll always hold the previous sum, which will always be numeric. Because the current value, cv
, can be non-numeric (NaN
), we use ||0
on it to skip that value in the array. This is terrific if you want to break up a sentence and get the sum of the numbers in it. Here's a more detailed example:
let num_of_fruits = `
This is a sentence where 1.25 values are oranges
and 2.5 values are apples. How many fruits are
there?
`.split(/\s/g).reduce((p,c)=>p+(parseFloat(c)||0), 0);
// num_of_fruits == 3.75
jQuery:
var arr = ["20.0","40.1","80.2","400.3"],
sum = 0;
$.each(arr,function(){sum+=parseFloat(this) || 0;});
What the above gets you:
123
or "123"
), floating point string or number ("123.4"
or 123.4
), or even text (abc
)I've had the same issue when some ASP.NET installation was corrupted. In that case they suggest running aspnet_regiis -i -enable
How about something like this?
<html>
<head>
<script type="text/javascript">
var HoverListener = {
addElem: function( elem, callback, delay )
{
if ( delay === undefined )
{
delay = 1000;
}
var hoverTimer;
addEvent( elem, 'mouseover', function()
{
hoverTimer = setTimeout( callback, delay );
} );
addEvent( elem, 'mouseout', function()
{
clearTimeout( hoverTimer );
} );
}
}
function tester()
{
alert( 'hi' );
}
// Generic event abstractor
function addEvent( obj, evt, fn )
{
if ( 'undefined' != typeof obj.addEventListener )
{
obj.addEventListener( evt, fn, false );
}
else if ( 'undefined' != typeof obj.attachEvent )
{
obj.attachEvent( "on" + evt, fn );
}
}
addEvent( window, 'load', function()
{
HoverListener.addElem(
document.getElementById( 'test' )
, tester
);
HoverListener.addElem(
document.getElementById( 'test2' )
, function()
{
alert( 'Hello World!' );
}
, 2300
);
} );
</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>
You should actually create a class:
class accum:
def __init__(self):
self.acc = 0
def accumulator(self, var2add, end):
if not end:
self.acc+=var2add
return self.acc
I got the same issue when I ran mongod command after installing it on Windows10. I stopped the mongodb service and started it again. Working like a charm
Command to stop mongodb service (in windows): net stop mongodb
Command to start mongodb server: mongod --dbpath PATH_TO_DATA_FOLDER
I had similar problems. The one downside is that with cin.ignore()
, you have to press enter 1 more time, which messes with the program.
select unique is not valid syntax for what you are trying to do
you want to use either select distinct or select distinctrow
And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.
the below query by itself will only provide distinct values
select col from table1
union
select col from table2
if you did want duplicates you would have to do
select col from table1
union all
select col from table2
Create a folder ${USER_HOME}/.mvn
and put a file called maven.config
in it.
The content should be:
-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true
Hope this helps.
That's work for me. Where myList is some unknown kind of list.
IEnumerable myEnum = myList as IEnumerable;
Type entryType = myEnum.AsQueryable().ElementType;
One way I can imagine is to use a linked list to implement such a scenario, if you need all the numbers entered before the user enters something which indicates the loop termination. (posting as the first option, because have never done this for user input, it just seemed to be interesting. Wasteful but artistic)
Another way is to do buffered input. Allocate a buffer, fill it, re-allocate, if the loop continues (not elegant, but the most rational for the given use-case).
I don't consider the described to be elegant though. Probably, I would change the use-case (the most rational).
I have a project where the source files are in in a folder below the project folder. When I copied the project folder without the source folder and opened the copied project, the source files are not missing but found at the old location. I closed the project, copied also the source folder, and re-opened the project. Now, the project magically references the copied source files (both the new path showed up on "save as" and a change in a file has been saved in the copied version).
There is a caveat: If not both old and new project folders are below a used library folder, the above-mentioned magic discards also the absolute reference to the library and expects it under the same relative path.
I tried this with VS Express 2012.
The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.
The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.
<td bgcolor="#your_color" background="your_image.jpg">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>
<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>
<![endif]-->
<p>Text over background image.</p>
<!--[if gte mso 9]>
</v:shape>
<![endif]-->
</td>
You need it to install development iPhone applications on development devices.
Here's how to create one, and the reference for this answer:
http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone
Another link: http://iphone.timefold.com/provisioning.html
Yes.
From this article:
https://lwn.net/Articles/542629/
The new socket option allows multiple sockets on the same host to bind to the same port
$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding
<select id="myId">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>`
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
contents in my backup_settings.ini file
[Settings]
year = 2020
python code for reading
import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year")
print(year)
for writing or updating
from pathlib import Path
import configparser
myfile = Path('backup_settings.ini') #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))
output
[Settings]
year = 2050
day = sunday
Have a look at jQuery scroll view (demo here). Here is the git hub repository for that experimental project. Look at their html to see what files need to be included and what attributes to add to the elements you want to be scrollable.
I have used this to be able to scroll div elements horizontally on touch devices.
Forms in C# are classes that inherit the Form
base class.
You can show a popup by creating an instance of the class and calling ShowDialog()
.
Simply specify whether you want the time to be greater, smaller, or equal to the time you want, using, respectively:
find . -cmin +<time>
find . -cmin -<time>
find . -cmin <time>
In your case, for example, the files with last edition in a maximum of 5 minutes, are given by:
find . -cmin -5
I found the simplest way is to put this in your overrides. Sorry for my unimaginative color choice
.my-btn {
//@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
@include button-variant(red, white, blue);
}
Bootstrap 4 Alpha SASS Example
.my-btn {
//.button-variant(@btn-primary-color; @btn-primary-bg; @btn-primary-border);
.button-variant(red; white; blue);
}
.my-btn {
//@include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
@include button-variant(red, white, blue);
}
.btn-primary {
//.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
.buttonBackground(red, white);
}
.btn-primary {
//@include buttonBackground($btnPrimaryBackground, $btnPrimaryBackgroundHighlight);
@include buttonBackground(red, white);
}
It will take care of the hover/actives for you
From the comments, if you want to lighten the button instead of darken when using black (or just want to inverse) you need to extend the class a bit further like so:
.my-btn {
// @include button-variant($btn-primary-color, $btn-primary-bg, $btn-primary-border);
$color: #fff;
$background: #000;
$border: #333;
@include button-variant($color, $background, $border);
// override the default darkening with lightening
&:hover,
&:focus,
&.focus,
&:active,
&.active,
.open > &.dropdown-toggle {
color: $color;
background-color: lighten($background, 20%); //10% default
border-color: lighten($border, 22%); // 12% default
}
}
My solution was to make all the parents 100% and set a specific percentage for each row:
html, body,div[class^="container"] ,.column {
height: 100%;
}
.row0 {height: 10%;}
.row1 {height: 40%;}
.row2 {height: 50%;}
datetime.datetime.fromtimestamp
will do, if you know the time zone, you could produce the same output as with time.gmtime
>>> datetime.datetime.fromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 11, 19, 54)
or
>>> datetime.datetime.utcfromtimestamp(1284286794)
datetime.datetime(2010, 9, 12, 10, 19, 54)
Just for fun this works in JS 1.8.5
var obj = {a: 1, b: 2, c: 3};
Object.keys(obj)[0]; // "a"
This matches the same order that you would see doing
for (o in obj) { ... }
I used this FileSaver.js. In my case with csv files, i did this (in coffescript):
$.ajax
url: "url-to-server"
data: "data-to-send"
success: (csvData)->
blob = new Blob([csvData], { type: 'text/csv' })
saveAs(blob, "filename.csv")
I think for most complicated case, the data must be processed properly. Under the hood FileSaver.js implement the same approach of the answer of Jonathan Amend.
I like Roger Cruz's answer of:
width: fit-content;
and I just want to add that you can use
padding: 0px 10px;
to add a nice 10px padding on the right and left side of the text in the button. Otherwise the text would be right up along the edge of the button and that wouldn't look good.
Here is how we solved it
a Users table looked like this
Users
-------------------------------------------------
id | name | address | phone | email | created_on | updated_on
And the business requirement changed and we were in a need to check all previous addresses and phone numbers a user ever had. new schema looks like this
Users (the data that won't change over time)
-------------
id | name
UserData (the data that can change over time and needs to be tracked)
-------------------------------------------------
id | id_user | revision | city | address | phone | email | created_on
1 | 1 | 0 | NY | lake st | 9809 | @long | 2015-10-24 10:24:20
2 | 1 | 2 | Tokyo| lake st | 9809 | @long | 2015-10-24 10:24:20
3 | 1 | 3 | Sdny | lake st | 9809 | @long | 2015-10-24 10:24:20
4 | 2 | 0 | Ankr | lake st | 9809 | @long | 2015-10-24 10:24:20
5 | 2 | 1 | Lond | lake st | 9809 | @long | 2015-10-24 10:24:20
To find the current address of any user, we search for UserData with revision DESC and LIMIT 1
To get the address of a user between a certain period of time we can use created_on bewteen (date1 , date 2)
The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.
To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:
Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.
Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:
Source: http://stevesouders.com/docs/web20expo-20090402.ppt
So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:
<div class="column">
<img class="custom-style" alt="appropriate alt text" />
</div>
I think you 're looking for the solution described in this answer Exclude methods from code coverage with Cobertura Keep in mind that if you're using Sonar 3.2 you have specify that your coverage tool is cobertura and not jacoco ( default ), which doesn't support this kind of feature yet
You can use git reset --soft
to change the version you want to have as parent for the changes you have in your index and working tree. The cases where this is useful are rare. Sometimes you might decide that the changes you have in your working tree should belong onto a different branch. Or you can use this as a simple way to collapse several commits into one (similar to squash/fold).
See this answer by VonC for a practical example: Squash the first two commits in Git?
Yes You can either set [disabled]= "true" or if it is an radio button or checkbox then you can simply use disable
For radio button:
<md-radio-button disabled>Select color</md-radio-button>
For dropdown:
<ng-select (selected)="someFunction($event)" [disabled]="true"></ng-select>
Like @amalBit's answer, register a listener to global layout and calculate the difference of dectorView's visible bottom and its proposed bottom, if the difference is bigger than some value(guessed IME's height), we think IME is up:
final EditText edit = (EditText) findViewById(R.id.edittext);
edit.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (keyboardShown(edit.getRootView())) {
Log.d("keyboard", "keyboard UP");
} else {
Log.d("keyboard", "keyboard Down");
}
}
});
private boolean keyboardShown(View rootView) {
final int softKeyboardHeight = 100;
Rect r = new Rect();
rootView.getWindowVisibleDisplayFrame(r);
DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
int heightDiff = rootView.getBottom() - r.bottom;
return heightDiff > softKeyboardHeight * dm.density;
}
the height threshold 100 is the guessed minimum height of IME.
This works for both adjustPan and adjustResize.
in angular2 2.1.1 I was not able to catch the exception using the (data),(error) pattern, so I implemented it using .catch(...).
It's nice because it can be used with all other Observable chained methods like .retry .map etc.
import {Observable} from 'rxjs/Rx';
Http
.put(...)
.catch(err => {
notify('UI error handling');
return Observable.throw(err); // observable needs to be returned or exception raised
})
.subscribe(data => ...) // handle success
from documentation:
Returns
(Observable): An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
TL;DR Just add
-- $(git diff --staged --name-only)
for your git<pathspec>
parameter
git stash -- $(git diff --staged --name-only)
And to add a message simply:
git stash push -m "My work in progress" -- $(git diff --staged --name-only)
Tested on v2.17.1 and v2.21.0.windows.1
Limitations:
- Please be aware that this will stash every single thing, if you have no files staged.
- Also if you have a file that is only partially staged ( i.e. only some changed lines, are staged while some other changed lines are not), then the whole file will get stashed (including unstaged lines).
From cppreference, one of the std::unique_ptr
constructors is
explicit unique_ptr( pointer p ) noexcept;
So to create a new std::unique_ptr
is to pass a pointer to its constructor.
unique_ptr<int> uptr (new int(3));
Or it is the same as
int *int_ptr = new int(3);
std::unique_ptr<int> uptr (int_ptr);
The different is you don't have to clean up after using it. If you don't use std::unique_ptr
(smart pointer), you will have to delete it like this
delete int_ptr;
when you no longer need it or it will cause a memory leak.
For ones that looking this solution in React, If you want to use the spread operator inside style, you should use: babel-plugin-transform-object-rest-spread.
Install it by npm module and configure your .babelrc as such:
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}
Then you can use like...
const sizing = { width: 200, height: 200 }
<div
className="dragon-avatar-image-background"
style={{ backgroundColor: blue, ...sizing }}
/>
More info: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/
You can find the target element in event.target
:
$(document).click(function(event) {
console.log($(event.target).text());
});
References:
A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('right,left,up,down', function(e, handler){
switch(handler.key){
case "right":console.log('right');break
case "left":console.log('left');break
case "up":console.log('up');break
case "down":console.log('down');break
}
});
You should write textcolor in xml as
android:textColor="@color/text_color"
or
android:textColor="#FFFFFF"
For styling each directional arrows(left, right,top and bottom), we have to select each arrow using CSS attribute selector and then style them individually.
Trick: Top arrow must have border color only on top side and transparent on other 3 sides. Other directional arrows also need to be styled this way.
click here for Working Jsfiddle Link
Here is the simple CSS,
.tooltip-inner { background-color:#8447cf;}
[data-placement="top"] + .tooltip > .tooltip-arrow { border-top-color: #8447cf;}
[data-placement="right"] + .tooltip > .tooltip-arrow { border-right-color: #8447cf;}
[data-placement="bottom"] + .tooltip > .tooltip-arrow {border-bottom-color: #8447cf;}
[data-placement="left"] + .tooltip > .tooltip-arrow {border-left-color: #8447cf; }
I had a user control which sat on page in a free form way, not constrained by another container, and the contents within the user control would not auto size but expand to the full size of what the user control was handed.
To get the user control to simply size to its content, for height only, I placed it into a grid with on row set to auto size such as this:
<Grid Margin="0,60,10,200">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<controls1:HelpPanel x:Name="HelpInfoPanel"
Visibility="Visible"
Width="570"
HorizontalAlignment="Right"
ItemsSource="{Binding HelpItems}"
Background="#FF313131" />
</Grid>
I'd like to add to the above answers, you could directly use
df = pd.read_fwf('output_list.txt')
fwf stands for fixed width formatted lines.
Try with this:
import os
os.system('clear')