I have tried this then i fixed my issue. It will calculate all media-breakpoint automatically by given rate (base-size/rate-size)
$base-size: 16;
$rate-size-xl: 24;
// set default size for all cases;
:root {
--size: #{$base-size};
}
// if it's smaller then LG it will set size rate to 16/16;
// example: if size set to 14px, it will be 14px * 16 / 16 = 14px
@include media-breakpoint-down(lg) {
:root {
--size: #{$base-size};
}
}
// if it is bigger then XL it will set size rate to 24/16;
// example: if size set to 14px, it will be 14px * 24 / 16 = 21px
@include media-breakpoint-up(xl) {
:root {
--size: #{$rate-size-xl};
}
}
@function size($px) {
@return calc(#{$px} / $base-size * var(--size));
}
div {
font-size: size(14px);
width: size(150px);
}
If you have Tortoise SVN, like I do, take the google link, and ONLY copy the URL.
Regular- (svn checkout http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter-read-only)
Modified to URL- (http://wittytwitter.googlecode.com/svn/trunk/ wittytwitter)
Create a folder, right click the empty space. You can Browse Repo or just download it all via checkout.
I don't know whether you have to be a Google member or not, but I signed up just in case. Have fun with the code.
Misanthropy
I'm sure you have your reasons, but just in case... you should also consider using a "merge" query instead:
begin
merge into some_table st
using (select 'some' name, 'values' value from dual) v
on (st.name=v.name)
when matched then update set st.value=v.value
when not matched then insert (name, value) values (v.name, v.value);
end;
(modified the above to be in the begin/end block; obviously you can run it independantly of the procedure too).
In Xcode 4
- Product menu > Manage Schemes
- Select the scheme thats having debugging problems (if only one choose that)
- Click Edit button at bottom
- Edit Scheme dialog appears
- in left panel click on Run APPNAME.app
- on Right hand panel make sure youre on INFO tab
- look for drop down DEBUGGER:
- someone had set this to None
- set to LLDB if this is your preferred debugger
- can also change BUILD CONFIGURATION drop down to Debug
- but I have other targets set to AdHoc which debug fine once Debugger is set
I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.
There is an easy way to check socket connection state via poll
call. First, you need to poll socket, whether it has POLLIN
event.
read
will return more than zero.POLLIN
will be set to 0 in revents
POLLIN
flag will be set to one and read will return 0.Here is small code snippet:
int client_socket_1, client_socket_2;
if ((client_socket_1 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s1");
abort();
}
if ((client_socket_2 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s2");
abort();
}
pollfd pfd[]={{client_socket_1,POLLIN,0},{client_socket_2,POLLIN,0}};
char sock_buf[1024];
while (true)
{
poll(pfd,2,5);
if (pfd[0].revents & POLLIN)
{
int sock_readden = read(client_socket_1, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_2, sock_buf, sock_readden);
}
if (pfd[1].revents & POLLIN)
{
int sock_readden = read(client_socket_2, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_1, sock_buf, sock_readden);
}
}
If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:
div#wrapper {
position: absolute;
width: 100%;
text-align: center;
}
Remember that in order to position an element absolutely, the parent element must be positioned relatively.
You can use this code:
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.setConnectTimeout(TIME_OUT);
conection.connect();
// Getting file length
int lenghtOfFile = conection.getContentLength();
// Create a Input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream to write file
OutputStream output = new FileOutputStream(
"/sdcard/9androidnet.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (SocketTimeoutException e) {
connectionTimeout=true;
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"
The quick answer is User = System.Web.HttpContext.Current.User
Ensure your web.config has the following authentication element.
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>
Further Reading: Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application
I copied and pasted this into my .vimrc file:
" size of a hard tabstop
set tabstop=4
" always uses spaces instead of tab characters
set expandtab
" size of an "indent"
set shiftwidth=4
The first 2 settings mean that when I press Tab I get 4 spaces.
The third setting means that when I do V>
(i.e. visual and indent) I also get 4 spaces.
Not as comprehensive as the accepted answer but it might help people who just want something to copy and paste.
The code below could explain in its own right, how http://thismachine.info/ is able to show which operating system someone is using.
What it does is that, it sniffs your core operating system model, for example windows nt 5.1
as my own.
It then passes windows nt 5.1/i to Windows XP as the operating system.
Using: '/windows nt 5.1/i' => 'Windows XP',
from an array.
You could say guesswork, or an approximation yet nonetheless pretty much bang on.
Borrowed from an answer on SO https://stackoverflow.com/a/15497878/
<?php
$user_agent = $_SERVER['HTTP_USER_AGENT'];
function getOS() {
global $user_agent;
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value)
if (preg_match($regex, $user_agent))
$os_platform = $value;
return $os_platform;
}
function getBrowser() {
global $user_agent;
$browser = "Unknown Browser";
$browser_array = array(
'/msie/i' => 'Internet Explorer',
'/firefox/i' => 'Firefox',
'/safari/i' => 'Safari',
'/chrome/i' => 'Chrome',
'/edge/i' => 'Edge',
'/opera/i' => 'Opera',
'/netscape/i' => 'Netscape',
'/maxthon/i' => 'Maxthon',
'/konqueror/i' => 'Konqueror',
'/mobile/i' => 'Handheld Browser'
);
foreach ($browser_array as $regex => $value)
if (preg_match($regex, $user_agent))
$browser = $value;
return $browser;
}
$user_os = getOS();
$user_browser = getBrowser();
$device_details = "<strong>Browser: </strong>".$user_browser."<br /><strong>Operating System: </strong>".$user_os."";
print_r($device_details);
echo("<br /><br /><br />".$_SERVER['HTTP_USER_AGENT']."");
?>
Footnotes:
(Jan. 19/14) There was a suggested edit on Jan. 18, 2014 to add /msie|trident/i
by YJSoft a new member on SO.
The comment read as:
Comment: because msie11's ua doesn't include msie (it includes trident instead)
I researched this for a bit, and found a few links explaining the Trident string.
Although the edit was rejected (not by myself, but by some of the other editors), it's worth reading up on the links above, and to use your proper judgement.
As per a question asked about detecting SUSE, have found this piece of code at the following URL:
Additional code:
/* return Operating System */
function operating_system_detection(){
if ( isset( $_SERVER ) ) {
$agent = $_SERVER['HTTP_USER_AGENT'];
}
else {
global $HTTP_SERVER_VARS;
if ( isset( $HTTP_SERVER_VARS ) ) {
$agent = $HTTP_SERVER_VARS['HTTP_USER_AGENT'];
}
else {
global $HTTP_USER_AGENT;
$agent = $HTTP_USER_AGENT;
}
}
$ros[] = array('Windows XP', 'Windows XP');
$ros[] = array('Windows NT 5.1|Windows NT5.1)', 'Windows XP');
$ros[] = array('Windows 2000', 'Windows 2000');
$ros[] = array('Windows NT 5.0', 'Windows 2000');
$ros[] = array('Windows NT 4.0|WinNT4.0', 'Windows NT');
$ros[] = array('Windows NT 5.2', 'Windows Server 2003');
$ros[] = array('Windows NT 6.0', 'Windows Vista');
$ros[] = array('Windows NT 7.0', 'Windows 7');
$ros[] = array('Windows CE', 'Windows CE');
$ros[] = array('(media center pc).([0-9]{1,2}\.[0-9]{1,2})', 'Windows Media Center');
$ros[] = array('(win)([0-9]{1,2}\.[0-9x]{1,2})', 'Windows');
$ros[] = array('(win)([0-9]{2})', 'Windows');
$ros[] = array('(windows)([0-9x]{2})', 'Windows');
// Doesn't seem like these are necessary...not totally sure though..
//$ros[] = array('(winnt)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'Windows NT');
//$ros[] = array('(windows nt)(([0-9]{1,2}\.[0-9]{1,2}){0,1})', 'Windows NT'); // fix by bg
$ros[] = array('Windows ME', 'Windows ME');
$ros[] = array('Win 9x 4.90', 'Windows ME');
$ros[] = array('Windows 98|Win98', 'Windows 98');
$ros[] = array('Windows 95', 'Windows 95');
$ros[] = array('(windows)([0-9]{1,2}\.[0-9]{1,2})', 'Windows');
$ros[] = array('win32', 'Windows');
$ros[] = array('(java)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,2})', 'Java');
$ros[] = array('(Solaris)([0-9]{1,2}\.[0-9x]{1,2}){0,1}', 'Solaris');
$ros[] = array('dos x86', 'DOS');
$ros[] = array('unix', 'Unix');
$ros[] = array('Mac OS X', 'Mac OS X');
$ros[] = array('Mac_PowerPC', 'Macintosh PowerPC');
$ros[] = array('(mac|Macintosh)', 'Mac OS');
$ros[] = array('(sunos)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'SunOS');
$ros[] = array('(beos)([0-9]{1,2}\.[0-9]{1,2}){0,1}', 'BeOS');
$ros[] = array('(risc os)([0-9]{1,2}\.[0-9]{1,2})', 'RISC OS');
$ros[] = array('os/2', 'OS/2');
$ros[] = array('freebsd', 'FreeBSD');
$ros[] = array('openbsd', 'OpenBSD');
$ros[] = array('netbsd', 'NetBSD');
$ros[] = array('irix', 'IRIX');
$ros[] = array('plan9', 'Plan9');
$ros[] = array('osf', 'OSF');
$ros[] = array('aix', 'AIX');
$ros[] = array('GNU Hurd', 'GNU Hurd');
$ros[] = array('(fedora)', 'Linux - Fedora');
$ros[] = array('(kubuntu)', 'Linux - Kubuntu');
$ros[] = array('(ubuntu)', 'Linux - Ubuntu');
$ros[] = array('(debian)', 'Linux - Debian');
$ros[] = array('(CentOS)', 'Linux - CentOS');
$ros[] = array('(Mandriva).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)', 'Linux - Mandriva');
$ros[] = array('(SUSE).([0-9]{1,3}(\.[0-9]{1,3})?(\.[0-9]{1,3})?)', 'Linux - SUSE');
$ros[] = array('(Dropline)', 'Linux - Slackware (Dropline GNOME)');
$ros[] = array('(ASPLinux)', 'Linux - ASPLinux');
$ros[] = array('(Red Hat)', 'Linux - Red Hat');
// Loads of Linux machines will be detected as unix.
// Actually, all of the linux machines I've checked have the 'X11' in the User Agent.
//$ros[] = array('X11', 'Unix');
$ros[] = array('(linux)', 'Linux');
$ros[] = array('(amigaos)([0-9]{1,2}\.[0-9]{1,2})', 'AmigaOS');
$ros[] = array('amiga-aweb', 'AmigaOS');
$ros[] = array('amiga', 'Amiga');
$ros[] = array('AvantGo', 'PalmOS');
//$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1}-([0-9]{1,2}) i([0-9]{1})86){1}', 'Linux');
//$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1} i([0-9]{1}86)){1}', 'Linux');
//$ros[] = array('(Linux)([0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}(rel\.[0-9]{1,2}){0,1})', 'Linux');
$ros[] = array('[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{1,3}', 'Linux');
$ros[] = array('(webtv)/([0-9]{1,2}\.[0-9]{1,2})', 'WebTV');
$ros[] = array('Dreamcast', 'Dreamcast OS');
$ros[] = array('GetRight', 'Windows');
$ros[] = array('go!zilla', 'Windows');
$ros[] = array('gozilla', 'Windows');
$ros[] = array('gulliver', 'Windows');
$ros[] = array('ia archiver', 'Windows');
$ros[] = array('NetPositive', 'Windows');
$ros[] = array('mass downloader', 'Windows');
$ros[] = array('microsoft', 'Windows');
$ros[] = array('offline explorer', 'Windows');
$ros[] = array('teleport', 'Windows');
$ros[] = array('web downloader', 'Windows');
$ros[] = array('webcapture', 'Windows');
$ros[] = array('webcollage', 'Windows');
$ros[] = array('webcopier', 'Windows');
$ros[] = array('webstripper', 'Windows');
$ros[] = array('webzip', 'Windows');
$ros[] = array('wget', 'Windows');
$ros[] = array('Java', 'Unknown');
$ros[] = array('flashget', 'Windows');
// delete next line if the script show not the right OS
//$ros[] = array('(PHP)/([0-9]{1,2}.[0-9]{1,2})', 'PHP');
$ros[] = array('MS FrontPage', 'Windows');
$ros[] = array('(msproxy)/([0-9]{1,2}.[0-9]{1,2})', 'Windows');
$ros[] = array('(msie)([0-9]{1,2}.[0-9]{1,2})', 'Windows');
$ros[] = array('libwww-perl', 'Unix');
$ros[] = array('UP.Browser', 'Windows CE');
$ros[] = array('NetAnts', 'Windows');
$file = count ( $ros );
$os = '';
for ( $n=0 ; $n<$file ; $n++ ){
if ( preg_match('/'.$ros[$n][0].'/i' , $agent, $name)){
$os = @$ros[$n][1].' '.@$name[2];
break;
}
}
return trim ( $os );
}
Edit: April 12, 2015
I noticed a question yesterday that could be relevant to this Q&A and may be helpful for some. In regards to:
Mozilla/5.0 (Linux; Android 4.4.2; SAMSUNG-GT-I9505 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36
Another edit, and adding a reference link that was asked (and answered/accepted today, Nov. 4/16) which may be of use.
Consult the Q&A here on Stack:
You cannot create a method inside another method, move private boolean checkInternetConnection() {
method out of onCreate
After executing the below regex, your answer is in the first capture.
/^(.*?)\.txt/
Forward declaring things in C++ is very useful because it dramatically speeds up compilation time. You can forward declare several things in C++ including: struct
, class
, function
, etc...
But can you forward declare an enum
in C++?
No you can't.
But why not allow it? If it were allowed you could define your enum
type in your header file, and your enum
values in your source file. Sounds like it should be allowed right?
Wrong.
In C++ there is no default type for enum
like there is in C# (int). In C++ your enum
type will be determined by the compiler to be any type that will fit the range of values you have for your enum
.
What does that mean?
It means that your enum
's underlying type cannot be fully determined until you have all of the values of the enum
defined. Which mans you cannot separate the declaration and definition of your enum
. And therefore you cannot forward declare an enum
in C++.
The ISO C++ standard S7.2.5:
The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than
int
unless the value of an enumerator cannot fit in anint
orunsigned int
. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value ofsizeof()
applied to an enumeration type, an object of enumeration type, or an enumerator, is the value ofsizeof()
applied to the underlying type.
You can determine the size of an enumerated type in C++ by using the sizeof
operator. The size of the enumerated type is the size of its underlying type. In this way you can guess which type your compiler is using for your enum
.
What if you specify the type of your enum
explicitly like this:
enum Color : char { Red=0, Green=1, Blue=2};
assert(sizeof Color == 1);
Can you then forward declare your enum
?
No. But why not?
Specifying the type of an enum
is not actually part of the current C++ standard. It is a VC++ extension. It will be part of C++0x though.
Take out bottom button from the nestedscrollview and take linearlayout as parent. Add bottom and nestedscrollview as thier children. It will work absolutely fine. In manifest for the activity use this - this will raise the button when the keyboard is opened
android:windowSoftInputMode="adjustResize|stateVisible"
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.core.widget.NestedScrollView xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/input_city_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="32dp"
android:layout_marginEnd="20dp"
android:hint="@string/city_name"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/city_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"
android:lines="1"
android:maxLength="100"
android:textSize="16sp" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:onClick="onSubmit"
android:padding="12dp"
android:text="@string/string_continue"
android:textColor="#FFFFFF"
app:layout_constraintBottom_toBottomOf="parent" />
</LinearLayout>
I didn't like any of the implementations (because they use a Regex which is an expensive operation, or a library which is an overkill if you only need one method), so I ended up using the java.net.URI class with some extra checks, and limiting the protocols to: http, https, file, ftp, mailto, news, urn.
And yes, catching exceptions can be an expensive operation, but probably not as bad as Regular Expressions:
final static Set<String> protocols, protocolsWithHost;
static {
protocolsWithHost = new HashSet<String>(
Arrays.asList( new String[]{ "file", "ftp", "http", "https" } )
);
protocols = new HashSet<String>(
Arrays.asList( new String[]{ "mailto", "news", "urn" } )
);
protocols.addAll(protocolsWithHost);
}
public static boolean isURI(String str) {
int colon = str.indexOf(':');
if (colon < 3) return false;
String proto = str.substring(0, colon).toLowerCase();
if (!protocols.contains(proto)) return false;
try {
URI uri = new URI(str);
if (protocolsWithHost.contains(proto)) {
if (uri.getHost() == null) return false;
String path = uri.getPath();
if (path != null) {
for (int i=path.length()-1; i >= 0; i--) {
if ("?<>:*|\"".indexOf( path.charAt(i) ) > -1)
return false;
}
}
}
return true;
} catch ( Exception ex ) {}
return false;
}
You can use:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
Source: Java API 7.0
It seems as of now, the only solution is still to install SublimeREPL.
To extend on Raghav's answer, it can be quite annoying to have to go into the Tools->SublimeREPL->Python->Run command every time you want to run a script with input, so I devised a quick key binding that may be handy:
To enable it, go to Preferences->Key Bindings - User, and copy this in there:
[
{"keys":["ctrl+r"] ,
"caption": "SublimeREPL: Python - RUN current file",
"command": "run_existing_window_command",
"args":
{
"id": "repl_python_run",
"file": "config/Python/Main.sublime-menu"
}
},
]
Naturally, you would just have to change the "keys" argument to change the shortcut to whatever you'd like.
Instead of letting the business layer decide how it’s best to fetch all the associations that are needed by the View layer, OSIV (Open Session in View) forces the Persistence Context to stay open so that the View layer can trigger the Proxy initialization, as illustrated by the following diagram.
OpenSessionInViewFilter
calls the openSession
method of the underlying SessionFactory
and obtains a new Session
.Session
is bound to the TransactionSynchronizationManager
.OpenSessionInViewFilter
calls the doFilter
of the javax.servlet.FilterChain
object reference and the request is further processedDispatcherServlet
is called, and it routes the HTTP request to the underlying PostController
.PostController
calls the PostService
to get a list of Post
entities.PostService
opens a new transaction, and the HibernateTransactionManager
reuses the same Session
that was opened by the OpenSessionInViewFilter
.PostDAO
fetches the list of Post
entities without initializing any lazy association.PostService
commits the underlying transaction, but the Session
is not closed because it was opened externally.DispatcherServlet
starts rendering the UI, which, in turn, navigates the lazy associations and triggers their initialization.OpenSessionInViewFilter
can close the Session
, and the underlying database connection is released as well.At first glance, this might not look like a terrible thing to do, but, once you view it from a database perspective, a series of flaws start to become more obvious.
The service layer opens and closes a database transaction, but afterward, there is no explicit transaction going on. For this reason, every additional statement issued from the UI rendering phase is executed in auto-commit mode. Auto-commit puts pressure on the database server because each transaction issues a commit at end, which can trigger a transaction log flush to disk. One optimization would be to mark the Connection
as read-only which would allow the database server to avoid writing to the transaction log.
There is no separation of concerns anymore because statements are generated both by the service layer and by the UI rendering process. Writing integration tests that assert the number of statements being generated requires going through all layers (web, service, DAO) while having the application deployed on a web container. Even when using an in-memory database (e.g. HSQLDB) and a lightweight webserver (e.g. Jetty), these integration tests are going to be slower to execute than if layers were separated and the back-end integration tests used the database, while the front-end integration tests were mocking the service layer altogether.
The UI layer is limited to navigating associations which can, in turn, trigger N+1 query problems. Although Hibernate offers @BatchSize
for fetching associations in batches, and FetchMode.SUBSELECT
to cope with this scenario, the annotations are affecting the default fetch plan, so they get applied to every business use case. For this reason, a data access layer query is much more suitable because it can be tailored to the current use case data fetch requirements.
Last but not least, the database connection is held throughout the UI rendering phase which increases connection lease time and limits the overall transaction throughput due to congestion on the database connection pool. The more the connection is held, the more other concurrent requests are going to wait to get a connection from the pool.
Unfortunately, OSIV (Open Session in View) is enabled by default in Spring Boot, and OSIV is really a bad idea from a performance and scalability perspective.
So, make sure that in the application.properties
configuration file, you have the following entry:
spring.jpa.open-in-view=false
This will disable OSIV so that you can handle the LazyInitializationException
the right way.
Starting with version 2.0, Spring Boot issues a warning when OSIV is enabled by default, so you can discover this problem long before it affects a production system.
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
Directory listing varies greatly according to the OS/platform under consideration. This is because, various Operating systems using their own internal system calls to achieve this.
A solution to this problem would be to look for a library which masks this problem and portable. Unfortunately, there is no solution that works on all platforms flawlessly.
On POSIX compatible systems, you could use the library to achieve this using the code posted by Clayton (which is referenced originally from the Advanced Programming under UNIX book by W. Richard Stevens). this solution will work under *NIX systems and would also work on Windows if you have Cygwin installed.
Alternatively, you could write a code to detect the underlying OS and then call the appropriate directory listing function which would hold the 'proper' way of listing the directory structure under that OS.
I had this issue with the Jenkins Git plugin after authentication issues with GitLab. Jenkins was reporting 'hudson.plugins.git.GitException:[...]stderr: GitLab: The project you were looking for could not be found. fatal: Could not read from remote repository.'
However if I did a 'git clone' or 'git fetch' direct from the Jenkins box (command line) it worked without issue.
The issue was resolved by deleting the entire /workspace directory in the Jenkins jobs folder for that particular job, e.g.
rm -Rf $JENKINS_HOME/jobs/myJenkinsJob/workspace/
Presumably the local .git folder had got stale/corrupted ?
splattne's answer probably covered most of everything so I won't repeat the same thing, but: inline
and inline-block
behave differently with the direction
CSS property.
Within the next snippet you see one two
(in order) is rendered, like it does in LTR layouts. I suspect the browser here auto-detected the English part as LTR text and rendered it from left to right.
body {_x000D_
text-align: right;_x000D_
direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
display: inline;_x000D_
}
_x000D_
<h2>_x000D_
??? ????? ????_x000D_
<span>one</span>_x000D_
<span>two</span>_x000D_
</h2>
_x000D_
However, if I go ahead and set display
to inline-block
, the browser appears to respect the direction
property and render the elements from right to left in order, so that two one
is rendered.
body {_x000D_
text-align: right;_x000D_
direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
display: inline-block;_x000D_
}
_x000D_
<h2>_x000D_
??? ????? ????_x000D_
<span>one</span>_x000D_
<span>two</span>_x000D_
</h2>
_x000D_
I don't know if there are any other quirks to this, I only found about this empirically on Chrome.
To see how the repr works within a class, run the following code, first with and then without the repr method.
class Coordinate (object):
def __init__(self,x,y):
self.x = x
self.y = y
def getX(self):
# Getter method for a Coordinate object's x coordinate.
# Getter methods are better practice than just accessing an attribute directly
return self.x
def getY(self):
# Getter method for a Coordinate object's y coordinate
return self.y
def __repr__(self): #remove this and the next line and re-run
return 'Coordinate(' + str(self.getX()) + ',' + str(self.getY()) + ')'
>>>c = Coordinate(2,-8)
>>>print(c)
The for
loop runs immediately to completion while all your asynchronous operations are started. When they complete some time in the future and call their callbacks, the value of your loop index variable i
will be at its last value for all the callbacks.
This is because the for
loop does not wait for an asynchronous operation to complete before continuing on to the next iteration of the loop and because the async callbacks are called some time in the future. Thus, the loop completes its iterations and THEN the callbacks get called when those async operations finish. As such, the loop index is "done" and sitting at its final value for all the callbacks.
To work around this, you have to uniquely save the loop index separately for each callback. In Javascript, the way to do that is to capture it in a function closure. That can either be done be creating an inline function closure specifically for this purpose (first example shown below) or you can create an external function that you pass the index to and let it maintain the index uniquely for you (second example shown below).
As of 2016, if you have a fully up-to-spec ES6 implementation of Javascript, you can also use let
to define the for
loop variable and it will be uniquely defined for each iteration of the for
loop (third implementation below). But, note this is a late implementation feature in ES6 implementations so you have to make sure your execution environment supports that option.
Use .forEach() to iterate since it creates its own function closure
someArray.forEach(function(item, i) {
asynchronousProcess(function(item) {
console.log(i);
});
});
Create Your Own Function Closure Using an IIFE
var j = 10;
for (var i = 0; i < j; i++) {
(function(cntr) {
// here the value of i was passed into as the argument cntr
// and will be captured in this function closure so each
// iteration of the loop can have it's own value
asynchronousProcess(function() {
console.log(cntr);
});
})(i);
}
Create or Modify External Function and Pass it the Variable
If you can modify the asynchronousProcess()
function, then you could just pass the value in there and have the asynchronousProcess()
function the cntr back to the callback like this:
var j = 10;
for (var i = 0; i < j; i++) {
asynchronousProcess(i, function(cntr) {
console.log(cntr);
});
}
Use ES6 let
If you have a Javascript execution environment that fully supports ES6, you can use let
in your for
loop like this:
const j = 10;
for (let i = 0; i < j; i++) {
asynchronousProcess(function() {
console.log(i);
});
}
let
declared in a for
loop declaration like this will create a unique value of i
for each invocation of the loop (which is what you want).
Serializing with promises and async/await
If your async function returns a promise, and you want to serialize your async operations to run one after another instead of in parallel and you're running in a modern environment that supports async
and await
, then you have more options.
async function someFunction() {
const j = 10;
for (let i = 0; i < j; i++) {
// wait for the promise to resolve before advancing the for loop
await asynchronousProcess();
console.log(i);
}
}
This will make sure that only one call to asynchronousProcess()
is in flight at a time and the for
loop won't even advance until each one is done. This is different than the previous schemes that all ran your asynchronous operations in parallel so it depends entirely upon which design you want. Note: await
works with a promise so your function has to return a promise that is resolved/rejected when the asynchronous operation is complete. Also, note that in order to use await
, the containing function must be declared async
.
Run asynchronous operations in parallel and use Promise.all()
to collect results in order
function someFunction() {
let promises = [];
for (let i = 0; i < 10; i++) {
promises.push(asynchonousProcessThatReturnsPromise());
}
return Promise.all(promises);
}
someFunction().then(results => {
// array of results in order here
console.log(results);
}).catch(err => {
console.log(err);
});
They've changed it now. (Oct 2010)
Log into iPhone developer website: http://developer.apple.com/
Then click on "Provisioning Portal" on the right hand sidebar menu (right at the top).
On the next page click "Provisioning" in the left sidebar menu
Then you'll see your provisioning profile/s, and the 'renew' button/s - Press it :)
Check the PASSWORD_LOCK_TIME
parameter. If it is set to 1 then you won't be able to unlock the password for 1 day even after you issue the alter user unlock
command.
select b.* from
(select
`lms_attendance`.`user` AS `user`,
max(`lms_attendance`.`time`) AS `time`
from `lms_attendance`
group by
`lms_attendance`.`user`) a
join
(select *
from `lms_attendance` ) b
on a.user = b.user
and a.time = b.time
I found an easier way to do it and it works perfectly even if you don't know the path where the chrome is located.
First of all, you have to paste this code in the top of the module.
Option Explicit
Private pWebAddress As String
Public Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _
(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
After that you have to create this two modules:
Sub LoadExplorer()
LoadFile "Chrome.exe" ' Here you are executing the chrome. exe
End Sub
Sub LoadFile(FileName As String)
ShellExecute 0, "Open", FileName, "http://test.123", "", 1 ' You can change the URL.
End Sub
With this you will be able (if you want) to set a variable for the url or just leave it like hardcode.
Ps: It works perfectly for others browsers just changing "Chrome.exe" to opera, bing, etc.
I had faced the same issue but in my case logs are shown when other devices are connected and not shown when my device is connected.
It took me days and finally, the issue resolved when I restarted my phone.
Strings don't encapsulate color information. Are you thinking of setting the color in a console or in the GUI?
I found the best way to handle this (for me) is to use the following:
Dim MyString as String
MyString = Application.ThisCell.Address
Range(MyString).Select
Hope this helps.
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesif (window.console && 'function' === typeof window.console.log) { window.console.log(o); }
Ugrading from an older app to rails 3.1, including the csrf meta tag is still not solving it. On the rubyonrails.org blog, they give some upgrade tips, and specifically this line of jquery which should go in the head section of your layout:
$(document).ajaxSend(function(e, xhr, options) {
var token = $("meta[name='csrf-token']").attr("content");
xhr.setRequestHeader("X-CSRF-Token", token);
});
taken from this blog post: http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails.
In my case, the session was being reset upon each ajax request. Adding the above code solved that issue.
You can use bellow code to get route name in blade file
request()->route()->uri
Today, lots of people opt for doing session management with JWTs without being aware of what they are giving up for the sake of perceived simplicity. My answer elaborates on the 2nd part of the questions:
What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?
Are there other options? Is using JWT not suited for this scenario?
JWTs are capable of supporting basic session management with some limitations. Being self-describing tokens, they don't require any state on the server-side. This makes them appealing. For instance, if the service doesn't have a persistence layer, it doesn't need to bring one in just for session management.
However, statelessness is also the leading cause of their shortcomings. Since they are only issued once with fixed content and expiration, you can't do things you would like to with a typical session management setup.
Namely, you can't invalidate them on-demand. This means you can't implement a secure logout as there is no way to expire already issued tokens. You also can't implement idle timeout for the same reason. One solution is to keep a blacklist, but that introduces state.
I wrote a post explaining these drawbacks in more detail. To be clear, you can work around these by adding more complexity (sliding sessions, refresh tokens, etc.)
As for other options, if your clients only interact with your service via a browser, I strongly recommend using a cookie-based session management solution. I also compiled a list authentication methods currently widely used on the web.
Download the wheel file (for example dlb-0.5.0-py3-none-any.whl) from Pypi and
pip install dlb-0.5.0-py3-none-any.whl
Post installation instructions are not clear:
==> Source [/.../google-cloud-sdk/completion.bash.inc] in your profile to enable shell command completion for gcloud.
==> Source [/.../google-cloud-sdk/path.bash.inc] in your profile to add the Google Cloud SDK command line tools to your $PATH.
I had to actually add the following lines of code in my .bash_profile
for gcloud
to work:
source '/.../google-cloud-sdk/completion.bash.inc'
source '/.../google-cloud-sdk/path.bash.inc'
TL;DR Make a copy or alias of your python.exe with name python2.7.exe
My python 2.7 was installed as
D:\app\Python27\python.exe
I always got this error no matter how I set (and verified) PYTHON env variable:
gyp ERR! stack Error: Can't find Python executable "python2.7", you can set the PYTHON env variable. gyp ERR! stack at failNoPython (C:\Program Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\configure.js:103:14)
The reason for this was that in node-gyp's configure.js the python executable was resolved like:
var python = gyp.opts.python || process.env.PYTHON || 'python'
And it turned out that gyp.opts.python had value 'python2.7' thus overriding process.env.PYTHON.
I resolved this by creating an alias for python.exe executable with name node-gyp was looking for:
D:\app\Python27>mklink python2.7.exe python.exe
You need admin rights for this operation.
Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:
<button class="btn btn-large btn-primary newclass" type="button">Submit</button>
and the CSS would be:
.btn.newclass {width:25%; display:block; margin: 0 auto;}
The "width" value is up to you, and you can play with that to get the right look.
Steve
It's not possible to retrieve data from RDBMS for user friends data for data which cross more than half a billion at a constant time so Facebook implemented this using a hash database (no SQL) and they opensourced the database called Cassandra.
So every user has its own key and the friends details in a queue; to know how cassandra works look at this:
For Python 3.2+ simple-date is a wrapper around pytz that tries to simplify things.
If you have a time
then
SimpleDate(time).convert(tz="...")
may do what you want. But timezones are quite complex things, so it can get significantly more complicated - see the the docs.
For those who tried gkalpak answer and it did not work,
be aware that chrome will add the content script to a needed page only when your extension enabled during chrome launch and also a good idea restart browser after making these changes
To solve this error, it is enough to add from google.colab import files
in your code!
It appears as though you need to explicitly set a font, and change the line-height
and height
as needed. Assuming 'Times New Roman' is your browser's default font:
span {_x000D_
display: inline-block;_x000D_
font-size: 50px;_x000D_
background-color: green;_x000D_
/*new:*/_x000D_
font-family: 'Times New Roman';_x000D_
line-height: 34px;_x000D_
height: 35px;_x000D_
}
_x000D_
<link href='http://fonts.googleapis.com/css?family=Tinos' rel='stylesheet' type='text/css'>_x000D_
<span>_x000D_
BIG TEXT_x000D_
</span>
_x000D_
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
Make sure Your TableView Delegate are working as well. if not then in your story board or in .xib press and hold Control + right click on tableView drag and Drop to your Current ViewController. swift 2.0
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60.0;
}
For no errors.
error_reporting(0);
or for just not strict
error_reporting(E_ALL ^ E_STRICT);
and if you ever want to display all errors again, use
error_reporting(-1);
You don't need to copy things around, webpack works different than gulp. Webpack is a module bundler and everything you reference in your files will be included. You just need to specify a loader for that.
So if you write:
var myImage = require("./static/myImage.jpg");
Webpack will first try to parse the referenced file as JavaScript (because that's the default). Of course, that will fail. That's why you need to specify a loader for that file type. The file- or url-loader for instance take the referenced file, put it into webpack's output folder (which should be build
in your case) and return the hashed url for that file.
var myImage = require("./static/myImage.jpg");
console.log(myImage); // '/build/12as7f9asfasgasg.jpg'
Usually loaders are applied via the webpack config:
// webpack.config.js
module.exports = {
...
module: {
loaders: [
{ test: /\.(jpe?g|gif|png|svg|woff|ttf|wav|mp3)$/, loader: "file" }
]
}
};
Of course you need to install the file-loader first to make this work.
The "Spring Boot" way is to use a CommandLineRunner
. Just add beans of that type and you are good to go. In Spring 4.1 (Boot 1.2) there is also a SmartInitializingBean
which gets a callback after everything has initialized. And there is SmartLifecycle
(from Spring 3).
Your question "what are they" is already answered above.
As far as debugging (your second question) though, and in developing libraries where you want to check for special input values, you may find the following functions useful in Windows C++:
_isnan(), _isfinite(), and _fpclass()
On Linux/Unix you should find isnan(), isfinite(), isnormal(), isinf(), fpclassify() useful (and you may need to link with libm by using the compiler flag -lm).
Thought this might be handy for others. Knowing regex is useful, kids. Stay in school.
Edit: Turned it into a handy dandy function!
let specificStatusCodeMappings = {
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
};
function getStatusCodeString(code) {
if (code >= 0 && code <= 999) {
return '(Unused)';
} else if (code >= 1016) {
if (code <= 1999) {
return '(For WebSocket standard)';
} else if (code <= 2999) {
return '(For WebSocket extensions)';
} else if (code <= 3999) {
return '(For libraries and frameworks)';
} else if (code <= 4999) {
return '(For applications)';
}
}
if (typeof(specificStatusCodeMappings[code]) !== 'undefined') {
return specificStatusCodeMappings[code];
}
return '(Unknown)';
}
Usage:
getStatusCodeString(1006); //'Abnormal Closure'
{
'0-999': '(Unused)',
'1016-1999': '(For WebSocket standard)',
'2000-2999': '(For WebSocket extensions)',
'3000-3999': '(For libraries and frameworks)',
'4000-4999': '(For applications)'
}
{
'1000': 'Normal Closure',
'1001': 'Going Away',
'1002': 'Protocol Error',
'1003': 'Unsupported Data',
'1004': '(For future)',
'1005': 'No Status Received',
'1006': 'Abnormal Closure',
'1007': 'Invalid frame payload data',
'1008': 'Policy Violation',
'1009': 'Message too big',
'1010': 'Missing Extension',
'1011': 'Internal Error',
'1012': 'Service Restart',
'1013': 'Try Again Later',
'1014': 'Bad Gateway',
'1015': 'TLS Handshake'
}
Source (with minor edits for terseness): https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes
Just add ?author=<emailaddress>
or ?author=<githubUserName>
to the url when viewing the "commits" section of a repo.
If you have already the Query String as a string, you can also use simple string manipulation:
int pos = queryString.ToLower().IndexOf("parameter=");
if (pos >= 0)
{
int pos_end = queryString.IndexOf("&", pos);
if (pos_end >= 0) // there are additional parameters after this one
queryString = queryString.Substring(0, pos) + queryString.Substring(pos_end + 1);
else
if (pos == 0) // this one is the only parameter
queryString = "";
else // this one is the last parameter
queryString=queryString.Substring(0, pos - 1);
}
<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
You can simply use if(yourElement)
var a = document.getElementById("elemA");_x000D_
var b = document.getElementById("elemB");_x000D_
_x000D_
if(a)_x000D_
console.log("elemA exists");_x000D_
else_x000D_
console.log("elemA does not exist");_x000D_
_x000D_
if(b)_x000D_
console.log("elemB exists");_x000D_
else_x000D_
console.log("elemB does not exist");
_x000D_
<div id="elemA"></div>
_x000D_
You can fix broken serialize string using following function, with multibyte character handling.
function repairSerializeString($value)
{
$regex = '/s:([0-9]+):"(.*?)"/';
return preg_replace_callback(
$regex, function($match) {
return "s:".mb_strlen($match[2]).":\"".$match[2]."\"";
},
$value
);
}
Here is a complete working example that uses the linked list implemented java.util. You can just copy paste the code below inside a main() method.
LinkedList<Integer> dList1 = new LinkedList<Integer>();
LinkedList<Integer> dList2 = new LinkedList<Integer>();
LinkedList<Integer> dListMerged = new LinkedList<Integer>();
dList1.addLast(1);
dList1.addLast(8);
dList1.addLast(12);
dList1.addLast(15);
dList1.addLast(85);
dList2.addLast(2);
dList2.addLast(3);
dList2.addLast(12);
dList2.addLast(24);
dList2.addLast(85);
dList2.addLast(185);
int i = 0;
int y = 0;
int dList1Size = dList1.size();
int dList2Size = dList2.size();
int list1Item = dList1.get(i);
int list2Item = dList2.get(y);
while (i < dList1Size || y < dList2Size) {
if (i < dList1Size) {
if (list1Item <= list2Item || y >= dList2Size) {
dListMerged.addLast(list1Item);
i++;
if (i < dList1Size) {
list1Item = dList1.get(i);
}
}
}
if (y < dList2Size) {
if (list2Item <= list1Item || i >= dList1Size) {
dListMerged.addLast(list2Item);
y++;
if (y < dList2Size) {
list2Item = dList2.get(y);
}
}
}
}
for(int x:dListMerged)
{
System.out.println(x);
}
class Program
{
static void Main(string[] args)
{
Task.Factory.StartNew(() => MyMethod("param value"));
}
private static void MyMethod(string p)
{
Console.WriteLine(p);
}
}
Use a Func<T1, T2, TResult>
delegate as the parameter type and pass it in to your Query
:
public List<IJob> getJobs(Func<FullTimeJob, Student, FullTimeJob> lambda)
{
using (SqlConnection connection = new SqlConnection(getConnectionString())) {
connection.Open();
return connection.Query<FullTimeJob, Student, FullTimeJob>(sql,
lambda,
splitOn: "user_id",
param: parameters).ToList<IJob>();
}
}
You would call it:
getJobs((job, student) => {
job.Student = student;
job.StudentId = student.Id;
return job;
});
Or assign the lambda to a variable and pass it in.
You can use a transformation for your data frame:
df = pd.DataFrame(my_data condition)
df = df*1
ps -p $$
should work anywhere that the solutions involving ps -ef
and grep
do (on any Unix variant which supports POSIX options for ps
) and will not suffer from the false positives introduced by grepping for a sequence of digits which may appear elsewhere.
What is a CSS map file?
It is a JSON format file that links the CSS file to its source files, normally, files written in preprocessors (i.e., Less, Sass, Stylus, etc.), this is in order do a live debug to the source files from the web browser.
What is CSS preprocessor? Examples: Sass, Less, Stylus
It is a CSS generator tool that uses programming power to generate CSS robustly and quickly.
Escaping strings can be tricky - especially if you want to take unicode into account. I suppose XML is one of the simpler formats/languages to escape but still. I would recommend taking a look at the StringEscapeUtils class in Apache Commons Lang, and its handy escapeXml method.
It will be bigger in base64.
Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte. Also, there is a little padding overhead with Base64. Not all bits are used with Base64 because it was developed in the first place to encode binary data on systems that can only correctly process non-binary data.
That means that the encoded image will be around 33%-36% larger (33% from not using 2 of the bits per byte, plus possible padding accounting for the remaining 3%).
Other answers here provide solutions for triggering change detection cycles that will update component's view (which is not same as full re-render).
Full re-render, which would destroy and reinitialize component (calling all lifecycle hooks and rebuilding view) can be done by using ng-template
, ng-container
and ViewContainerRef
in following way:
<div>
<ng-container #outlet >
</ng-container>
</div>
<ng-template #content>
<child></child>
</ng-template>
Then in component having reference to both #outlet
and #content
we can clear outlets' content and insert another instance of child component:
@ViewChild("outlet", {read: ViewContainerRef}) outletRef: ViewContainerRef;
@ViewChild("content", {read: TemplateRef}) contentRef: TemplateRef<any>;
private rerender() {
this.outletRef.clear();
this.outletRef.createEmbeddedView(this.contentRef);
}
Additionally initial content should be inserted on AfterContentInit
hook:
ngAfterContentInit() {
this.outletRef.createEmbeddedView(this.contentRef);
}
Full working solution can be found here https://stackblitz.com/edit/angular-component-rerender .
Use npm outdated to discover dependencies that are out of date.
Use npm update to perform safe dependency upgrades.
Use npm install @latest to upgrade to the latest major version of a package.
Use npx npm-check-updates -u and npm install to upgrade all dependencies to their latest major versions.
Git is probably already tracking the file.
From the gitignore docs:
To stop tracking a file that is currently tracked, use git rm --cached.
Use this, replacing [project]
and [username]
with your info:
git rm --cached [project].xcodeproj/project.xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
git commit -m "Removed file that shouldn't be tracked"
Alternatively you can use the -a
option to git commit
that will add all files that have been modified or deleted.
Once you've removed the file from git, it will respect your .gitignore
.
var lowerCaseName = "Your Name".toLowerCase();
Please add below jQuery Migrate Plugin
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>
Like this:
>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'
This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4]
removes the same 4 characters from the end of the string:
>>>mystr[:-4]
'abcdefgh'
For more information on slicing see this Stack Overflow answer.
You can also use this function,
function optionDisable(selectId, optionIndices)
{
for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
{
document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
}
}
Building slightly off Ben's answer, I added attributes for the ID so I could use labels.
<%: Html.Label("isBlahYes", "Yes")%><%= Html.RadioButtonFor(model => model.blah, true, new { @id = "isBlahYes" })%>
<%: Html.Label("isBlahNo", "No")%><%= Html.RadioButtonFor(model => model.blah, false, new { @id = "isBlahNo" })%>
I hope this helps.
For the error 5, i did the opposite to the solution above. "The first Error 5: Access Denied error was resolved by giving permissions to the output directory to the NETWORK SERVICE account."
I changed mine to local account, instead of network service account, and because i was logged in as administrator it worked
It just means "different of", some languages uses !=
, others (like SQL) <>
Edit the tty configuration in /etc/init/tty*.conf
with a shellscript as a parameter :
(...)
exec /sbin/getty -n -l theInputScript.sh -8 38400 tty1
(...)
This is assuming that we're editing tty1 and the script that reads input is theInputScript.sh.
A word of warning this script is run as root, so when you are inputing stuff to it you have root priviliges. Also append a path to the location of the script.
Important: the script when it finishes, has to invoke the /sbin/login otherwise you wont be able to login in the terminal.
This will contain the full class (which may be multiple space separated classes, if the element has more than one class). In your code it will contain either "konbo" or "kinta":
event.target.className
You can use jQuery to check for classes by name:
$(event.target).hasClass('konbo');
and to add or remove them with addClass and removeClass.
There is a better and quicker way now (Chrome version 59.x.x.):
Right-click onto the reload-icon (left of the url-field) and you get a drop-down menu, select the third option: 'empty Cache and Hard reload'.
This option is only available when the developer tools are open. (Notice the difference to option 2: 'Hard reload' -cmd-shift-R). No cache emptying here!
use this,it got fixed for me, over centOS 7
<Directory /usr/share/phpMyAdmin/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
Or you can do that with ES6 template literal:
<a :href="`/job/${r.id}`"
There are a lot of good answers here with very accurate relational algebra examples. Here is a very simplified answer that might be helpful for amateur or novice coders with SQL coding dilemmas.
Basically, more often than not, JOIN
queries boil down to two cases:
For a SELECT
of a subset of A
data:
INNER JOIN
when the related B
data you are looking for MUST exist per database design;LEFT JOIN
when the related B
data you are looking for MIGHT or MIGHT NOT exist per database design.Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC
option ensures that GCC produces such code.
If you using ajax to load modal's body such way and want to be able to reload it's content
<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here -->
</div>
</div>
</div>
use
<script>
$(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).removeData('bs.modal');
});
});
</script>
Recently refactored to obtain the location of the code, learn some good ideas, and finally achieved a relatively perfect library and Demo.
//request all valid provider(network/gps)
private boolean requestAllProviderUpdates() {
checkRuntimeEnvironment();
checkPermission();
if (isRequesting) {
EasyLog.d("Request location update is busy");
return false;
}
long minTime = getCheckTimeInterval();
float minDistance = getCheckMinDistance();
if (mMapLocationListeners == null) {
mMapLocationListeners = new HashMap<>();
}
mValidProviders = getValidProviders();
if (mValidProviders == null || mValidProviders.isEmpty()) {
throw new IllegalArgumentException("Not available provider.");
}
for (String provider : mValidProviders) {
LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
if (location == null) {
EasyLog.e("LocationListener callback location is null.");
return;
}
printf(location);
mLastProviderTimestamp = location.getTime();
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
finishResult(location);
} else {
doLocationResult(location);
}
removeProvider(location.getProvider());
if (isEmptyValidProviders()) {
requestTimeoutMsgInit();
removeUpdates();
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
getLocationManager().requestLocationUpdates(provider, minTime, minDistance, locationListener);
mMapLocationListeners.put(provider, locationListener);
EasyLog.d("Location request %s provider update.", provider);
}
isRequesting = true;
return true;
}
//remove request update
public void removeUpdates() {
checkRuntimeEnvironment();
LocationManager locationManager = getLocationManager();
if (mMapLocationListeners != null) {
Set<String> keys = mMapLocationListeners.keySet();
for (String key : keys) {
LocationListener locationListener = mMapLocationListeners.get(key);
if (locationListener != null) {
locationManager.removeUpdates(locationListener);
EasyLog.d("Remove location update, provider is " + key);
}
}
mMapLocationListeners.clear();
isRequesting = false;
}
}
//Compared with the last successful position, to determine whether you need to filter
private boolean isNeedFilter(Location location) {
checkLocation(location);
if (mLastLocation != null) {
float distance = location.distanceTo(mLastLocation);
if (distance < getCheckMinDistance()) {
return true;
}
if (location.getAccuracy() >= mLastLocation.getAccuracy()
&& distance < location.getAccuracy()) {
return true;
}
if (location.getTime() <= mLastProviderTimestamp) {
return true;
}
}
return false;
}
private void doLocationResult(Location location) {
checkLocation(location);
if (isNeedFilter(location)) {
EasyLog.d("location need to filtered out, timestamp is " + location.getTime());
finishResult(mLastLocation);
} else {
finishResult(location);
}
}
//Return to the finished position
private void finishResult(Location location) {
checkLocation(location);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
float accuracy = location.getAccuracy();
long time = location.getTime();
String provider = location.getProvider();
if (mLocationResultListeners != null && !mLocationResultListeners.isEmpty()) {
String format = "Location result:<%f, %f> Accuracy:%f Time:%d Provider:%s";
EasyLog.i(String.format(format, latitude, longitude, accuracy, time, provider));
mLastLocation = location;
synchronized (this) {
Iterator<LocationResultListener> iterator = mLocationResultListeners.iterator();
while (iterator.hasNext()) {
LocationResultListener listener = iterator.next();
if (listener != null) {
listener.onResult(location);
}
iterator.remove();
}
}
}
}
Complete code: https://github.com/bingerz/FastLocation/blob/master/fastlocationlib/src/main/java/cn/bingerz/fastlocation/FastLocation.java
*Each request to complete the location, it is best to removeUpdates, otherwise the phone status bar will always display the positioning icon.
As a one-liner into vim:
:set tabstop=4 shiftwidth=4
For permanent setup, add these lines to ~/.vimrc:
set tabstop=4
set shiftwidth=4
NOTE: Add set expandtab
if you prefer 4-spaces indentation, instead of a tab indentation.
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';
SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
Simply from command prompt or Linux environment run the following command.
python -c 'import torch; print(torch.cuda.is_available())'
The above should print True
python -c 'import torch; print(torch.rand(2,3).cuda())'
This one should print the following:
tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')
I've adjusted Glenn Moss' answer to account for the fact that overflow div might not be at the top of the page.
parentDiv.scrollTop(parentDiv.scrollTop() + (innerListItem.position().top - parentDiv.position().top) - (parentDiv.height()/2) + (innerListItem.height()/2) )
I was using this on a google maps application with a responsive template. On resolution > 800px, the list was on the left side of the map. On resolution < 800 the list was below the map.
you would have to copy the current data to the new directory and to change your my.cnf
your MySQL.
[mysqld]
datadir=/your/new/dir/
tmpdir=/your/new/temp/
You have to copy the database when the server is not running.
With Spring Boot :
In the pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
Example in class Java
@Configuration
@Slf4j
public class MyAppConfig {
@Value("${foo}")
private String foo;
@Value("${bar}")
private String bar;
@Bean("foo")
public String foo() {
log.info("foo={}", foo);
return foo;
}
@Bean("bar")
public String bar() {
log.info("bar={}", bar);
return bar;
}
[ ... ]
In the properties files :
src/main/resources/application.properties
foo=all-env-foo
src/main/resources/application-rec.properties
bar=rec-bar
src/main/resources/application-prod.properties
bar=prod-bar
In the VM arguments of Application.java
-Dspring.profiles.active=[rec|prod]
Don't forget to run mvn command after modifying the properties !
mvn clean package -Dmaven.test.skip=true
In the log file for -Dspring.profiles.active=rec :
The following profiles are active: rec
foo=all-env-foo
bar=rec-bar
In the log file for -Dspring.profiles.active=prod :
The following profiles are active: prod
foo=all-env-foo
bar=prod-bar
In the log file for -Dspring.profiles.active=local :
Could not resolve placeholder 'bar' in value "${bar}"
Oups, I forget to create application-local.properties.
Ensure that the permissions on your home directory and on the home directory of the user on the host you're connecting to are set to 700 ( owning user rwx only to prevent others seeing the .ssh subdirectory ).
Then ensure that the ~/.ssh directory is also 700 ( user rwx ) and that the authorized_keys is 600 ( user rw ) .
Private keys in your ~/.ssh directory should be 600 or 400 ( user rw or user r )
you need to alter session
you can try before insert
sql : alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'
Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.
for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }
Your project is too large. You have too many methods. There can only be 65536 methods per application. see here https://code.google.com/p/android/issues/detail?id=7147#c6
double total = 44;
String total2= new Double(total).toString();
this code works
To include native libraries you need:
To create jar file, use the following snippet:
task nativeLibsToJar(type: Zip, description: 'create a jar archive of the native libs') {
destinationDir file("$buildDir/native-libs")
baseName 'native-libs'
extension 'jar'
from fileTree(dir: 'libs', include: '**/*.so')
into 'lib/'
}
tasks.withType(Compile) {
compileTask -> compileTask.dependsOn(nativeLibsToJar)
}
To include resulting file, paste the following line into "dependencies" section in "build.gradle" file:
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
Using directive it becomes easy and can be used throughout the application
HTML
<input type="text" placeholder="Enter value" numbersOnly>
As .keyCode()
and .which()
are deprecated, codes are checked using .key()
Referred from
Directive:
@Directive({
selector: "[numbersOnly]"
})
export class NumbersOnlyDirective {
@Input() numbersOnly:boolean;
navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
constructor(private _el: ElementRef) { }
@HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
if (
// Allow: Delete, Backspace, Tab, Escape, Enter, etc
this.navigationKeys.indexOf(e.key) > -1 ||
(e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
(e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
(e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
(e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
(e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
(e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
(e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
(e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
) {
return; // let it happen, don't do anything
}
// Ensure that it is a number and stop the keypress
if (e.key === ' ' || isNaN(Number(e.key))) {
e.preventDefault();
}
}
}
You can use AndroidAccessors
Plugin of Android Studio
to generate getter and setter without m as prefix to methods
Ex: mId;
Will generate getId()
and setId()
instead of getmId()
and setmId()
I use doctest[1] almost everywhere because I like the fact that I document and test my functions at the same time.
Have a look at this code:
def throw_up(something, gowrong=False):
"""
>>> throw_up('Fish n Chips')
Traceback (most recent call last):
...
Exception: Fish n Chips
>>> throw_up('Fish n Chips', gowrong=True)
'I feel fine!'
"""
if gowrong:
return "I feel fine!"
raise Exception(something)
if __name__ == '__main__':
import doctest
doctest.testmod()
If you put this example in a module and run it from the command line both test cases are evaluated and checked.
[1] Python documentation: 23.2 doctest -- Test interactive Python examples
This error would occur if any of the following variables were actually strings or null instead of arrays, in which case accessing them with an array syntax $var[$i]
would be like trying to access a specific character in a string:
$catagory
$task
$fullText
$dueDate
$empId
In short, everything in your insert query.
Perhaps the $catagory
variable is misspelled?
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
In PHP >= 7.1 this is possible. See this answer.
If you can modify the exceptions, use this answer.
If you can't, you could try catching all with Exception
and then check which exception was thrown with instanceof
.
try
{
/* something */
}
catch( Exception $e )
{
if ($e instanceof AError OR $e instanceof BError) {
// It's either an A or B exception.
} else {
// Keep throwing it.
throw $e;
}
}
But it would probably be better to use multiple catch blocks as described in aforementioned answer.
try
{
/* something */
}
catch( AError $e )
{
handler1( $e );
}
catch ( BError $b )
{
handler2( $e );
}
stringContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); capture
And YES! ... that cleared up the problem with ATS REST API: SharedKey works now! https://github.com/dotnet/runtime/issues/17036#issuecomment-212046628
Atom is still in beta (v0.123 as I'm writing this) but it's moving fast. Way faster than Sublime. New builds are released on a weekly basis, sometimes even few of them in the same week. In its short life span, it had more releases than Sublime which takes months to release a new feature or a bug fix. Here's an updated take on things looking back on the path Atom has taken since the launch of the beta:
Sublime has better performance than Atom. Simply because it's written in C++. Atom on the other hand is a web based desktop app built on top of Chromium, and while they take performance close to heart, it will be really hard or even impossible to reach the same speed and responsiveness. Last July Atom began using React and it gave it a nice performance boost but you can still feel the difference. Apart from that, if Atom’s performance issues will not push users away - Sublime better speed up the release cycle, brush up its small UX tweaks, and consider letting in more contributors because this is where Atom is winning.
Atom's package ecosystem is also growing really fast, it might not be as big as Sublime's at the moment but I have a feeling that with GitHub at it's back it will keep growing even faster. It probably has the majority of IDE like plug-ins you can think of. A major difference right now is that it can't handle files bigger than 2MB so it's something to keep in mind.
The one thing you'll notice first is that the Sublime minimap is gone! Other than that, the first impression is that Atom looks almost the same as Sublime. I wrote a more in depth comparison about it in this blog post.
No easy straightforward way to port your Sublime configurations, packages and such as far as I know.
It's been said elaborately, just as "the short answer":
static variable (class)
lifetime = program runtime (1)
visibility = determined by access modifiers (private/protected/public)
static variable (global scope)
lifetime = program runtime (1)
visibility = the compilation unit it is instantiated in (2)
heap variable
lifetime = defined by you (new to delete)
visibility = defined by you (whatever you assign the pointer to)
stack variable
visibility = from declaration until scope is exited
lifetime = from declaration until declaring scope is exited
(1) more exactly: from initialization until deinitialization of the compilation unit (i.e. C / C++ file). Order of initialization of compilation units is not defined by the standard.
(2) Beware: if you instantiate a static variable in a header, each compilation unit gets its own copy.
For AWK haters, and for simplicity, this contraption works for me:
help:
make -qpRr $(lastword $(MAKEFILE_LIST)) | egrep -v '(^(\.|:|#|\s|$)|=)' | cut -d: -f1
(for use outside a Makefile, just remove $(lastword ...)
or replace it with the Makefile path).
This solution will not work if you have "interesting" rule names but will work well for most simple setups. The main downside of a make -qp
based solution is (as in other answers here) that if the Makefile defines variable values using functions - they will still be executed regardless of -q
, and if using $(shell ...)
then the shell command will still be called and its side effects will happen. In my setup often the side effects of running shell functions is unwanted output to standard error, so I add 2>/dev/null
after the make command.
Please Try this one.
ImageView imageview1 = findViewById(R.id.imageView1);
imageview1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(YourActivity.this, "Here is your Text",Toast.LENGTH_SHORT).show();
}
});
In light of the "named functions show up in stack traces" argument, modern JavaScript engines are actually quite capable of representing anonymous functions.
As of this writing, V8, SpiderMonkey, Chakra and Nitro always refer to named functions by their names. They almost always refer to an anonymous function by its identifier if it has one.
SpiderMonkey can figure out the name of an anonymous function returned from another function. The rest can't.
If you really, really wanted your iterator and success callbacks to show up in the trace, you could name those too...
[].forEach(function iterator() {});
But for the most part it's not worth stressing over.
'use strict';
var a = function () {
throw new Error();
},
b = function b() {
throw new Error();
},
c = function d() {
throw new Error();
},
e = {
f: a,
g: b,
h: c,
i: function () {
throw new Error();
},
j: function j() {
throw new Error();
},
k: function l() {
throw new Error();
}
},
m = (function () {
return function () {
throw new Error();
};
}()),
n = (function () {
return function n() {
throw new Error();
};
}()),
o = (function () {
return function p() {
throw new Error();
};
}());
console.log([a, b, c].concat(Object.keys(e).reduce(function (values, key) {
return values.concat(e[key]);
}, [])).concat([m, n, o]).reduce(function (logs, func) {
try {
func();
} catch (error) {
return logs.concat('func.name: ' + func.name + '\n' +
'Trace:\n' +
error.stack);
// Need to manually log the error object in Nitro.
}
}, []).join('\n\n'));
func.name:
Trace:
Error
at a (http://localhost:8000/test.js:4:11)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: b
Trace:
Error
at b (http://localhost:8000/test.js:7:15)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: d
Trace:
Error
at d (http://localhost:8000/test.js:10:15)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name:
Trace:
Error
at a (http://localhost:8000/test.js:4:11)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: b
Trace:
Error
at b (http://localhost:8000/test.js:7:15)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: d
Trace:
Error
at d (http://localhost:8000/test.js:10:15)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name:
Trace:
Error
at e.i (http://localhost:8000/test.js:17:19)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: j
Trace:
Error
at j (http://localhost:8000/test.js:20:19)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: l
Trace:
Error
at l (http://localhost:8000/test.js:23:19)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name:
Trace:
Error
at http://localhost:8000/test.js:28:19
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: n
Trace:
Error
at n (http://localhost:8000/test.js:33:19)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27
func.name: p
Trace:
Error
at p (http://localhost:8000/test.js:38:19)
at http://localhost:8000/test.js:47:9
at Array.reduce (native)
at http://localhost:8000/test.js:44:27 test.js:42
func.name:
Trace:
a@http://localhost:8000/test.js:4:5
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: b
Trace:
b@http://localhost:8000/test.js:7:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: d
Trace:
d@http://localhost:8000/test.js:10:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name:
Trace:
a@http://localhost:8000/test.js:4:5
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: b
Trace:
b@http://localhost:8000/test.js:7:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: d
Trace:
d@http://localhost:8000/test.js:10:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name:
Trace:
e.i@http://localhost:8000/test.js:17:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: j
Trace:
j@http://localhost:8000/test.js:20:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: l
Trace:
l@http://localhost:8000/test.js:23:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name:
Trace:
m</<@http://localhost:8000/test.js:28:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: n
Trace:
n@http://localhost:8000/test.js:33:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: p
Trace:
p@http://localhost:8000/test.js:38:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: undefined
Trace:
Error
at a (http://localhost:8000/test.js:4:5)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at b (http://localhost:8000/test.js:7:9)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at d (http://localhost:8000/test.js:10:9)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at a (http://localhost:8000/test.js:4:5)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at b (http://localhost:8000/test.js:7:9)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at d (http://localhost:8000/test.js:10:9)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at e.i (http://localhost:8000/test.js:17:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at j (http://localhost:8000/test.js:20:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at l (http://localhost:8000/test.js:23:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at Anonymous function (http://localhost:8000/test.js:28:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at n (http://localhost:8000/test.js:33:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name: undefined
Trace:
Error
at p (http://localhost:8000/test.js:38:13)
at Anonymous function (http://localhost:8000/test.js:47:9)
at Global code (http://localhost:8000/test.js:42:1)
func.name:
Trace:
a@http://localhost:8000/test.js:4:22
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: b
Trace:
b@http://localhost:8000/test.js:7:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: d
Trace:
d@http://localhost:8000/test.js:10:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name:
Trace:
a@http://localhost:8000/test.js:4:22
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: b
Trace:
b@http://localhost:8000/test.js:7:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: d
Trace:
d@http://localhost:8000/test.js:10:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name:
Trace:
i@http://localhost:8000/test.js:17:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: j
Trace:
j@http://localhost:8000/test.js:20:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: l
Trace:
l@http://localhost:8000/test.js:23:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name:
Trace:
http://localhost:8000/test.js:28:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: n
Trace:
n@http://localhost:8000/test.js:33:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
func.name: p
Trace:
p@http://localhost:8000/test.js:38:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
Read about using docstrings in your Python code.
As per the Python docstring conventions:
The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
There will be no golden rule, but rather provide comments that mean something to the other developers on your team (if you have one) or even to yourself when you come back to it six months down the road.
A handle is a sort of pointer in that it is typically a way of referencing some entity.
It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.
For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.
The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.
It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.
Injection already existed in Java EE 5 with the @Resource, @PersistentUnit or @EJB annotations, for example. But it was limited to certain resources (datasource, EJB . . .) and into certain components (Servlets, EJBs, JSF backing bean . . .). With CDI you can inject nearly anything anywhere thanks to the @Inject annotation.
You can use the Session object
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')
tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log
You can also upload log from admin console : http://yoururl:4848
If you're having this problem in a stored procedure and you aren't able to use the key in the WHERE clause, you can solve this by declaring a variable that will hold the limit of the rows that should be updated and then use it in the update/delete query.
DELIMITER $
CREATE PROCEDURE myProcedure()
BEGIN
DECLARE the_limit INT;
SELECT COUNT(*) INTO the_limit
FROM my_table
WHERE my_column IS NULL;
UPDATE my_table
SET my_column = true
WHERE my_column IS NULL
LIMIT the_limit;
END$
If you just have a static svg string you want to include, you can use dangerouslySetInnerHTML
:
render: function() {
return <span dangerouslySetInnerHTML={{__html: "<svg>...</svg>"}} />;
}
and React will include the markup directly without processing it at all.
Add your dependencies like mongodb,web,jpa. Delete/clear the remainings.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
The following worked for me taken from the official Mozilla documentation Error.
function NotImplementedError(message) {
var instance = new Error(message);
instance.name = 'NotImplementedError';
Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
if (Error.captureStackTrace) {
Error.captureStackTrace(instance, NotImplementedError);
}
return instance;
}
NotImplementedError.prototype = Object.create(Error.prototype, {
constructor: {
value: Error,
enumerable: false,
writable: true,
configurable: true
}
});
The list of valid characters is in the XML specification:
Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */
[Ljava.lang.Object;
is the name for Object[].class
, the java.lang.Class
representing the class of array of Object
.
The naming scheme is documented in Class.getName()
:
If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).
If this class object represents a primitive type or
void
, then the name returned is the Java language keyword corresponding to the primitive type orvoid
.If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more
'['
characters representing the depth of the array nesting. The encoding of element type names is as follows:Element Type Encoding boolean Z byte B char C double D float F int I long J short S class or interface Lclassname;
Yours is the last on that list. Here are some examples:
// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx
The reason why the toString()
method on arrays returns String
in this format is because arrays do not @Override
the method inherited from Object
, which is specified as follows:
The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
Note: you can not rely on the toString()
of any arbitrary object to follow the above specification, since they can (and usually do) @Override
it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass()
on it (a final
method inherited from Object
) and then reflecting on the returned Class
object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).
toString
for arraysjava.util.Arrays
provides toString
overloads for primitive arrays and Object[]
. There is also deepToString
that you may want to use for nested arrays.
Here are some examples:
int[] nums = { 1, 2, 3 };
System.out.println(nums);
// [I@xxxxx
System.out.println(Arrays.toString(nums));
// [1, 2, 3]
int[][] table = {
{ 1, },
{ 2, 3, },
{ 4, 5, 6, },
};
System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]
System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]
There are also Arrays.equals
and Arrays.deepEquals
that perform array equality comparison by their elements, among many other array-related utility methods.
Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me.
Try Jquery Interface Elements here - http://interface.eyecon.ro/docs/carousel
Here's a sample. http://interface.eyecon.ro/demos/carousel.html
I looked around for a Jquery image carousel a few months ago and didn't find a good one so I gave up. This one was the best I could find.
if your signal is in the matrix X
, you make it zero-mean by removing the average:
X=X-mean(X(:));
and unit variance by dividing by the standard deviation:
X=X/std(X(:));
executemany accept array of tuples
https://www.postgresqltutorial.com/postgresql-python/insert/
""" array of tuples """
vendor_list = [(value1,)]
""" insert multiple vendors into the vendors table """
sql = "INSERT INTO vendors(vendor_name) VALUES(%s)"
conn = None
try:
# read database configuration
params = config()
# connect to the PostgreSQL database
conn = psycopg2.connect(**params)
# create a new cursor
cur = conn.cursor()
# execute the INSERT statement
cur.executemany(sql,vendor_list)
# commit the changes to the database
conn.commit()
# close communication with the database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
You'll want to use the formatting macros from inttypes.h.
See this question: Cross platform format string for variables of type size_t?
Its a bit late answer, but it covers merging images from urls using Picasso
MergeImageView
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.io.IOException;
import java.util.List;
public class MergeImageView extends ImageView {
private SparseArray<Bitmap> bitmaps = new SparseArray<>();
private Picasso picasso;
private final int DEFAULT_IMAGE_SIZE = 50;
private int MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE;
private int MAX_WIDTH = DEFAULT_IMAGE_SIZE * 2, MAX_HEIGHT = DEFAULT_IMAGE_SIZE * 2;
private String picassoRequestTag = null;
public MergeImageView(Context context) {
super(context);
}
public MergeImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MergeImageView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean isInEditMode() {
return true;
}
public void clearResources() {
if (bitmaps != null) {
for (int i = 0; i < bitmaps.size(); i++)
bitmaps.get(i).recycle();
bitmaps.clear();
}
// cancel picasso requests
if (picasso != null && AppUtils.ifNotNullEmpty(picassoRequestTag))
picasso.cancelTag(picassoRequestTag);
picasso = null;
bitmaps = null;
}
public void createMergedBitmap(Context context, List<String> imageUrls, String picassoTag) {
picasso = Picasso.with(context);
int count = imageUrls.size();
picassoRequestTag = picassoTag;
boolean isEven = count % 2 == 0;
// if url size are not even make MIN_IMAGE_SIZE even
MIN_IMAGE_SIZE = DEFAULT_IMAGE_SIZE + (isEven ? count / 2 : (count / 2) + 1);
// set MAX_WIDTH and MAX_HEIGHT to twice of MIN_IMAGE_SIZE
MAX_WIDTH = MAX_HEIGHT = MIN_IMAGE_SIZE * 2;
// in case of odd urls increase MAX_HEIGHT
if (!isEven) MAX_HEIGHT = MAX_WIDTH + MIN_IMAGE_SIZE;
// create default bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_wallpaper),
MIN_IMAGE_SIZE, MIN_IMAGE_SIZE, false);
// change default height (wrap_content) to MAX_HEIGHT
int height = Math.round(AppUtils.convertDpToPixel(MAX_HEIGHT, context));
setMinimumHeight(height * 2);
// start AsyncTask
for (int index = 0; index < count; index++) {
// put default bitmap as a place holder
bitmaps.put(index, bitmap);
new PicassoLoadImage(index, imageUrls.get(index)).execute();
// if you want parallel execution use
// new PicassoLoadImage(index, imageUrls.get(index)).(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private class PicassoLoadImage extends AsyncTask<String, Void, Bitmap> {
private int index = 0;
private String url;
PicassoLoadImage(int index, String url) {
this.index = index;
this.url = url;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// synchronous picasso call
return picasso.load(url).resize(MIN_IMAGE_SIZE, MIN_IMAGE_SIZE).tag(picassoRequestTag).get();
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Bitmap output) {
super.onPostExecute(output);
if (output != null)
bitmaps.put(index, output);
// create canvas
Bitmap.Config conf = Bitmap.Config.RGB_565;
Bitmap canvasBitmap = Bitmap.createBitmap(MAX_WIDTH, MAX_HEIGHT, conf);
Canvas canvas = new Canvas(canvasBitmap);
canvas.drawColor(Color.WHITE);
// if height and width are equal we have even images
boolean isEven = MAX_HEIGHT == MAX_WIDTH;
int imageSize = bitmaps.size();
int count = imageSize;
// we have odd images
if (!isEven) count = imageSize - 1;
for (int i = 0; i < count; i++) {
Bitmap bitmap = bitmaps.get(i);
canvas.drawBitmap(bitmap, bitmap.getWidth() * (i % 2), bitmap.getHeight() * (i / 2), null);
}
// if images are not even set last image width to MAX_WIDTH
if (!isEven) {
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmaps.get(count), MAX_WIDTH, MIN_IMAGE_SIZE, false);
canvas.drawBitmap(scaledBitmap, scaledBitmap.getWidth() * (count % 2), scaledBitmap.getHeight() * (count / 2), null);
}
// set bitmap
setImageBitmap(canvasBitmap);
}
}
}
xml
<com.example.MergeImageView
android:id="@+id/iv_thumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Example
List<String> urls = new ArrayList<>();
String picassoTag = null;
// add your urls
((MergeImageView)findViewById(R.id.iv_thumb)).
createMergedBitmap(MainActivity.this, urls,picassoTag);
It means "not equal to" (as in, the values in cells E37-N37 are not equal to ""
, or in other words, they are not empty.)
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
A little update to Evan Mulawski answer to make it shorter
List<string> allLinesText = File.ReadAllLines(fileName).ToList()
I came across this post while hunting down a solution for myself. By using chrome's inspector, I was able to determine that the striped color was being applied from the --bs-table-striped-color
tag.
overriding that tag in your css:
<style scoped>
table {
--bs-table-striped-color: #85d1ee;
}
</style>
IFrame is just an "internal frame". The reason why it can be considered less secure (than not using any kind of frame at all) is because you can include content that does not originate from your domain.
All this means is that you should trust whatever you include in an iFrame or a regular frame.
Frames and IFrames are equally secure (and insecure if you include content from an untrusted source).
You can use the Class XmlAttribute.
Eg:
XmlAttribute attr = xmlDoc.CreateAttribute("userName");
attr.Value = "Tushar";
node.Attributes.Append(attr);
You can always just use jQuery to add a class, .addClass
or .toggleClass
. Then you can keep all your styles in your CSS and out of your scripts.
Update (using renderer):
Note that the original Renderer service has now been deprecated in favor of Renderer2
as on Renderer2 official doc.
Furthermore, as pointed out by @GünterZöchbauer:
Actually using ElementRef is just fine. Also using ElementRef.nativeElement with Renderer2 is fine. What is discouraged is accessing properties of ElementRef.nativeElement.xxx directly.
You can achieve this by using elementRef
as well as by ViewChild
. however it's not recommendable to use elementRef
due to:
as pointed out by official ng2 documentation.
elementRef
(Direct Access):export class MyComponent {
constructor (private _elementRef : ElementRef) {
this._elementRef.nativeElement.querySelector('textarea').focus();
}
}
ViewChild
(better approach):<textarea #tasknote name="tasknote" [(ngModel)]="taskNote" placeholder="{{ notePlaceholder }}"
style="background-color: pink" (blur)="updateNote() ; noteEditMode = false " (click)="noteEditMode = false"> {{ todo.note }} </textarea> // <-- changes id to local var
export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
ngAfterViewInit() {
this.input.nativeElement.focus();
}
}
renderer
:export class MyComponent implements AfterViewInit {
@ViewChild('tasknote') input: ElementRef;
constructor(private renderer: Renderer2){
}
ngAfterViewInit() {
//using selectRootElement instead of depreaced invokeElementMethod
this.renderer.selectRootElement(this.input["nativeElement"]).focus();
}
}
Previous answer is not good for negative numbers. Use a short type instead of int
short iValue = -1400;
string sResult = iValue.ToString("X2");
Console.WriteLine("Value={0} Result={1}", iValue, sResult);
Now result is FA88
I use apache common IO to read a text file into a single string
String str = FileUtils.readFileToString(file);
simple and "clean". you can even set encoding of the text file with no hassle.
String str = FileUtils.readFileToString(file, "UTF-8");
Regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. Hence you can see that regular grammar is a subset of context-free grammar.
So for a palindrome for instance, is of the form,
S->ABA
A->something
B->something
You can clearly see that palindromes cannot be expressed in regular grammar since it needs to be either right or left linear and as such cannot have a non-terminal on both side.
Since regular grammars are non-ambiguous, there is only one production rule for a given non-terminal, whereas there can be more than one in the case of a context-free grammar.
Make an equals
check on the keySet()
of both HashMap
s.
NOTE:
If your Map
contains String
keys then it is no problem, but if your Map contains objA
type keys then you need to make sure that your class objA
implements equals()
.
When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:
{1, "one"}
{2, "two"}
{30, "thirty"}
You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.
After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.
This very helpful feature is now available starting at version 1.1.2 of AngularJS. It's considered unstable but I have used it (1.1.3) and it works fine.
Basically you can use a function to generate a templateUrl string. The function is passed the route parameters that you can use to build and return the templateUrl string.
var app = angular.module('app',[]);
app.config(
function($routeProvider) {
$routeProvider.
when('/', {templateUrl:'/home'}).
when('/users/:user_id',
{
controller:UserView,
templateUrl: function(params){ return '/users/view/' + params.user_id; }
}
).
otherwise({redirectTo:'/'});
}
);
Many thanks to https://github.com/lrlopez for the pull request.
const o = {
name: "Max",
location: "London"
};
for (const [key, value] of Object.entries(o)) {
console.log(`${key}: ${value}`);
}
CREATE TABLE someTable (
id serial PRIMARY KEY,
col1 int NOT NULL,
col2 int NOT NULL,
UNIQUE (col1, col2)
)
autoincrement
is not postgresql. You want a serial
.
If col1
and col2
make a unique and can't be null then they make a good primary key:
CREATE TABLE someTable (
col1 int NOT NULL,
col2 int NOT NULL,
PRIMARY KEY (col1, col2)
)
According to the man page of wget, there are a couple of options related to timeouts -- and there is a default read timeout of 900s -- so I say that, yes, it could timeout.
Here are the options in question :
-T seconds
--timeout=seconds
Set the network timeout to seconds seconds. This is equivalent to specifying
--dns-timeout
,--connect-timeout
, and--read-timeout
, all at the same time.
And for those three options :
--dns-timeout=seconds
Set the DNS lookup timeout to seconds seconds.
DNS lookups that don't complete within the specified time will fail.
By default, there is no timeout on DNS lookups, other than that implemented by system libraries.
--connect-timeout=seconds
Set the connect timeout to seconds seconds.
TCP connections that take longer to establish will be aborted.
By default, there is no connect timeout, other than that implemented by system libraries.
--read-timeout=seconds
Set the read (and write) timeout to seconds seconds.
The "time" of this timeout refers to idle time: if, at any point in the download, no data is received for more than the specified number of seconds, reading fails and the download is restarted.
This option does not directly affect the duration of the entire download.
I suppose using something like
wget -O - -q -t 1 --timeout=600 http://www.example.com/cron/run
should make sure there is no timeout before longer than the duration of your script.
(Yeah, that's probably the most brutal solution possible ^^ )
This helped me get to my answer. There are two php.ini
files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin
folder. When connecting to SQL through sqlsrv_connect
function, we are referring to the php.ini
file in the apache
folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
so late, but with ES6 no need extends it still work for me.... :)
let getArray = <T>(items: T[]): T[] => {
return new Array<T>().concat(items)
}
let myNumArr = getArray<number>([100, 200, 300]);
let myStrArr = getArray<string>(["Hello", "World"]);
myNumArr.push(1)
console.log(myNumArr)
With latest git you may use --patch
option
git stash push --patch # since 2.14.6
git stash save --patch # for older git versions
And git will ask you for each change in your files to add or not into stash.
You just answer y
or n
UPD
Alias for DOUBLE STASH:
git config --global alias.stash-staged '!bash -c "git stash --keep-index; git stash push -m "staged" --keep-index; git stash pop stash@{1}"'
Now you can stage your files and then run git stash-staged
.
As result your staged files will be saved into stash.
If you do not want to keep staged files and want move them into stash. Then you can add another alias and run git move-staged
:
git config --global alias.move-staged '!bash -c "git stash-staged;git commit -m "temp"; git stash; git reset --hard HEAD^; git stash pop"'
try this: //*[contains(@class, 'atag')]
Now in c++11 we have
#include <string>
string s = std::to_string(123);
Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
In this case, you might get some differences. Consider a line like:
"foo\tbar "
In this case, if you strip
, then you'll get {"foo":"bar"}
as the dictionary entry. If you don't strip, you'll get {"foo":"bar "}
(note the extra space at the end)
Note that if you use line.split()
instead of line.split('\t')
, you'll split on every whitespace character and the "strip
ing" will be done during splitting automatically. In other words:
line.strip().split()
is always identical to:
line.split()
but:
line.strip().split(delimiter)
Is not necessarily equivalent to:
line.split(delimiter)
You can do the following :-
$(document).ready(function(){
$("#id").trigger("click");
});
In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.
Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.
Possibly every remotely modern compiler implements #pragma pack
which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)
From C99 §6.7.2.1:
12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.
13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
Better yet, put --user-install
in your ~/.gemrc file so you don't have to type it every time
gem: --user-install
I know this is an old post, but figured I'd add my two penneth. How about the seldom used and oft' forgot Description list? With a simple bit of css you can get a really clean markup.
<dl>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
<dt></dt><dd></dd>
</dl>
take a look at this example http://codepen.io/butlerps/pen/wGmXPL
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
i found that this works for me
<input type="button" value="click me" onclick="window.open('http://someurl', 'targetname');">
This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:
clear() {
this.myForm.get('someControlName').reset()
}
With the Netbeans 10, commenting out the netbeans_jdkhome
setting in .../etc/netbeans.conf
doesn't do the job anymore. It is necessary to specify the right directory depending of 32/64 bitness.
E.g. for 64 bit application: netbeans_jdkhome="C:\Program Files\AdoptOpenJDK\jdk8u202-b08"
I'd suggest you use the TimeSpan
class for this.
public static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(80);
Console.WriteLine(t.ToString());
t = TimeSpan.FromSeconds(868693412);
Console.WriteLine(t.ToString());
}
Outputs:
00:01:20
10054.07:43:32
You can't modify the keys nor the values directly in a ForEach, but you can modify their members. E.g., this should work:
public class State {
public int Value;
}
...
Dictionary<string, State> colStates = new Dictionary<string,State>();
int OtherCount = 0;
foreach(string key in colStates.Keys)
{
double Percent = colStates[key].Value / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key].Value;
colStates[key].Value = 0;
}
}
colStates.Add("Other", new State { Value = OtherCount } );
DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.
An informational message is displayed if there are no active transactions in the log.
Though checkdate
is good, this seems much concise function to validate and also you can give formats. [Source]
function validateDate($date, $format = 'Y-m-d H:i:s') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
The extra ->format()
is needed for cases where the date is invalid but createFromFormat
still manages to create a DateTime object. For example:
// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');
// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');
The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:
arr = []
for i in array :
if i == "two" :
arr.push(i)
print(i)
You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.
The english equivalent of what you are doing is:
You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"
The reason 'i' is equal to "three" is because three was the last thing that was defined as I
the computer did:
i = "one"
i = "two"
i = "three"
print(["two"])
Because you asked it to.
If you want the index, go here If you want the values in an array, define the array, like this:
MyArray = [(i) for i in my_list if i=="two"]
I need to somehow query Google and ask: Is this access token valid for [email protected]?
No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.
The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.
So you need be from same domain as 'public interface'.
And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.
var test = $('input[name="testing"]:hidden');
test.val('work!');
Jauco posted a good solution in a comment, so I'm copying it here:
$(elem)
.contents()
.filter(function() {
return this.nodeType === 3; //Node.TEXT_NODE
});
Here's another one. It looks for the first and last non empty cell and builds are range from those. This also handles cases where your data is not rectangular and does not start in A1. Furthermore it handles merged cells as well, which .Find skips when executed from a macro, used on .Cells on a worksheet.
Function getUsedRange(ByRef sheet As Worksheet) As Range
' finds used range by looking for non empty cells
' works around bug in .Find that skips merged cells
' by starting at with the UsedRange (that may be too big)
' credit to https://contexturesblog.com/archives/2012/03/01/select-actual-used-range-in-excel-sheet/
' for the .Find commands
Dim excelsUsedRange As Range
Dim lastRow As Long
Dim lastCol As Long
Dim lastCell As Range
Dim firstRow As Long
Dim firstCol As Long
Dim firstCell As Range
Set excelsUsedRange = ActiveSheet.UsedRange
lastRow = excelsUsedRange.Find(What:="*", _
LookIn:=xlValues, SearchOrder:=xlRows, _
SearchDirection:=xlPrevious).Row
lastCol = excelsUsedRange.Find(What:="*", _
LookIn:=xlValues, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
Set lastCell = sheet.Cells(lastRow, lastCol)
firstRow = excelsUsedRange.Find(What:="*", After:=lastCell, _
LookIn:=xlValues, SearchOrder:=xlRows, _
SearchDirection:=xlNext).Row
firstCol = excelsUsedRange.Find(What:="*", After:=lastCell, _
LookIn:=xlValues, SearchOrder:=xlByColumns, _
SearchDirection:=xlNext).Row
Set firstCell = sheet.Cells(firstRow, firstCol)
Set getUsedRange = sheet.Range(firstCell, lastCell)
End Function
Instead of NOW()
you can use UNIX_TIMESTAMP()
also:
$update_query = "UPDATE db.tablename
SET insert_time=UNIX_TIMESTAMP()
WHERE username='$somename'";
Made the best/fastest part of this answer more re-usable & clear:
function getElByPropVal(myArray, prop, val){
for (var i = 0, length = myArray.length; i < length; i++) {
if (myArray[i][prop] == val){
return myArray[i];
}
}
}
For me even with [formGroup]
the error was popping up "Cannot find control with name:''"
.
It got fixed when I added ngModel
Value to the input box along with formControlName="fileName"
<form class="upload-form" [formGroup]="UploadForm">
<div class="row">
<div class="form-group col-sm-6">
<label for="fileName">File Name</label>
<!-- *** *** *** Adding [(ngModel)]="FileName" fixed the issue-->
<input type="text" class="form-control" id="fileName" [(ngModel)]="FileName"
placeholder="Enter file name" formControlName="fileName">
</div>
<div class="form-group col-sm-6">
<label for="selectedType">File Type</label>
<select class="form-control" formControlName="selectedType" id="selectedType"
(change)="TypeChanged(selectedType)" name="selectedType" disabled="true">
<option>Type 1</option>
<option>Type 2</option>
</select>
</div>
</div>
<div class="form-group">
<label for="fileUploader">Select {{selectedType}} file</label>
<input type="file" class="form-control-file" id="fileUploader" (change)="onFileSelected($event)">
</div>
<div class="w-80 text-right mt-3">
<button class="btn btn-primary mb-2 search-button cancel-button" (click)="cancelUpload()">Cancel</button>
<button class="btn btn-primary mb-2 search-button" (click)="uploadFrmwrFile()">Upload</button>
</div>
</form>
And in the controller
ngOnInit() {
this.UploadForm= new FormGroup({
fileName: new FormControl({value: this.FileName}),
selectedType: new FormControl({value: this.selectedType, disabled: true}, Validators.required),
frmwareFile: new FormControl({value: ['']})
});
}
I had the same problem, but none of the solutions worked for me, because the message The system cannot find the file specified
can be misleading in some special cases.
In my case, I use Notepad++ in combination with the registry redirect for notepad.exe. Unfortunately my path to Notepad++ in the registry was wrong.
So in fact the message The system cannot find the file specified
was telling me, that it cannot find the application (Notepad++) associated with the file type(*.txt), not the file itself.
That string2Bin can be written even more succinctly, and without any loops, to boot!
function string2Bin ( str ) {
return str.split("").map( function( val ) {
return val.charCodeAt( 0 );
} );
}
If you're willing to run X applications as well - use xpra together with "screen".
For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:
composer require phpseclib/phpseclib
Next, simply use it as follows:
use phpseclib\Net\SSH2;
// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
// Login failed, do something
}
$return_value = $ssh->exec('command');
[update 2015-09-28] Now Google lets you add custom domains (including naked domains) and setup SSL without the need of Google Apps. For details refer to here: https://cloud.google.com/appengine/docs/using-custom-domains-and-ssl?hl=en
I just discovered today (as of 2014-04-11) a new custom domain settings page is available from Google Developers Console:
1. Go to https://console.developers.google.com/project
2. Click on your project
3. On the left click "App Engine"
4. Click "Settings"
There you go! You can configure custom domain without the need of Google App account!
r = list(qs[:1])
if r:
return r[0]
return None
It's because the name
column on the bar
table does not have the UNIQUE constraint.
So imagine you have 2 rows on the bar
table that contain the name 'ams'
and you insert a row on baz
with 'ams'
on bar_fk
, which row on bar
would it be referring since there are two rows matching?
Use two single quotes to escape them in the sql statement. The double quotes should not be a problem:
SELECT 'How is my son''s school helping him learn? "Not as good as Stack Overflow would!"'
Print:
How is my son's school helping him learn? "Not as good as Stack Overflow would!"
You simply need to specify your current RE, followed by a letter/number followed by your current RE again:
^[A-Z0-9 _]*[A-Z0-9][A-Z0-9 _]*$
Since you've now stated they're Javascript REs, there's a useful site here where you can test the RE against input data.
If you want lowercase letters as well:
^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$
I've played around with select items before and without overriding the functionality with JavaScript, I don't think it's possible in Chrome. Whether you use a plugin or write your own code, CSS only is a no go for Chrome/Safari and as you said, Firefox is better at dealing with it.
Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.
Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
Well, the code you've given is invalid to start with - List
is a generic type, and it has an Add
method instead of add
etc.
But you could do something like:
List<Person> list = new List<Person>
{
new person{ID=1,Name="jhon",salary=2500},
new person{ID=2,Name="Sena",salary=1500},
new person{ID=3,Name="Max",salary=5500}.
new person{ID=4,Name="Gen",salary=3500}
};
// The "Where" LINQ operator filters a sequence
var highEarners = list.Where(p => p.salary > 3000);
foreach (var person in highEarners)
{
Console.WriteLine(person.Name);
}
If you want to learn details of what all the LINQ operators do, and how they can be implemented in LINQ to Objects, you might be interested in my Edulinq blog series.
Basically, the buttons in Twitter Bootstrap are controlled in CSS by ".btn{}". What you have to do is go to the CSS file and find where it says "btn" and change the color settings. However, it's not as simple as just doing that since you also have to change what color the button changes into when you highlight it, etc. To do THAT, you have to look for other tags in CSS like ".btn:hover{}", etc.
Changing it requires changing of the CSS. Here is a quick link to that file:
https://github.com/twbs/bootstrap/blob/master/dist/css/bootstrap.css
Using swing you could simply use a JLabel
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("<URL to your Animated GIF>");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
It is because you set the width:100%
which by definition only spans the width of the screen. You want to set the min-width:100%
which sets it to the width of the screen... with the ability to grow beyond that.
Also make sure you set min-width:100%
for body
and html
.
It is a very murky distinction, and in fact generally not a property of a language itself, but rather of the program you are using to execute code in that language.
However, most languages are used primarily in one form or the other, and yes, Java is essentially always compiled, while javascript is essentially always interpreted.
To compile source code is to run a program on it that generates a binary, executable file that, when run, has the behavior defined by the source. For instance, javac compiles human-readbale .java files into machine-readable .class files.
To interpret source code is run a program on it that produces the defined behavior right away, without generating an intermediary file. For instance, when your web browser loads stackoverflow.com, it interprets a bunch of javascript (which you can look at by viewing the page source) and produces lots of the nice effects these pages have - for instance, upvoting, or the little notifier bars across the top.
The below both ways works fine.
System.out.println("The Class Name is: " + this.getClass().getName());
System.out.println("The simple Class Name is: " + this.getClass().getSimpleName());
Output as below:
The Class Name is: package.Student
The simple Class Name is: Student
Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.
body {
background: url('../images/cat.ong');
background-size: cover;
background-position: center;
background-attachment: fixed;
}
I know this is old, but I have my own fix. Because I'm using source tree, this error happens because someone create a new branch. The source tree is confused about this. After I press "Refresh" button beside the "remote branch to pull" combobox, it seems that sourcetree has updated the branch list, and now I can pull successfully.
Aside from all the steps Luke and Vaiden recommended, I also had to rename all the customModule properties in my Storyboard to match the new name, and this has to be case sensitive.
VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.
The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.
If you want this in kotlin . And perfectly working
private fun exportDbFile() {
try {
//Existing DB Path
val DB_PATH = "/data/packagename/databases/mydb.db"
val DATA_DIRECTORY = Environment.getDataDirectory()
val INITIAL_DB_PATH = File(DATA_DIRECTORY, DB_PATH)
//COPY DB PATH
val EXTERNAL_DIRECTORY: File = Environment.getExternalStorageDirectory()
val COPY_DB = "/mynewfolder/mydb.db"
val COPY_DB_PATH = File(EXTERNAL_DIRECTORY, COPY_DB)
File(COPY_DB_PATH.parent!!).mkdirs()
val srcChannel = FileInputStream(INITIAL_DB_PATH).channel
val dstChannel = FileOutputStream(COPY_DB_PATH).channel
dstChannel.transferFrom(srcChannel,0,srcChannel.size())
srcChannel.close()
dstChannel.close()
} catch (excep: Exception) {
Toast.makeText(this,"ERROR IN COPY $excep",Toast.LENGTH_LONG).show()
Log.e("FILECOPYERROR>>>>",excep.toString())
excep.printStackTrace()
}
}
You can use the WebClient
Using System.Net;
WebClient client = new WebClient();
string downloadString = client.DownloadString("http://www.gooogle.com");
You can also use
./gradlew clean build
(Mac and Linux) -With ./
gradlew clean build
(Windows) -Without ./
it removes build folder, as well configure your modules and then build your project.
i use it before release any new app on playstore.
I know this is long stagnant topic, but in case anyone searches here is how I deal with multi table foreign keys. With this technique you do not have any DBA enforced cascade operations, so please make sure you deal with DELETE
and such in your code.
Table 1 Fruit
pk_fruitid, name
1, apple
2, pear
Table 2 Meat
Pk_meatid, name
1, beef
2, chicken
Table 3 Entity's
PK_entityid, anme
1, fruit
2, meat
3, desert
Table 4 Basket (Table using fk_s)
PK_basketid, fk_entityid, pseudo_entityrow
1, 2, 2 (Chicken - entity denotes meat table, pseudokey denotes row in indictaed table)
2, 1, 1 (Apple)
3, 1, 2 (pear)
4, 3, 1 (cheesecake)
SO Op's Example would look like this
deductions
--------------
type id name
1 khce1 gold
2 khsn1 silver
types
---------------------
1 employees_ce
2 employees_sn
I find that if I specify .row:nth-of-type(..)
, my other row's elements (for other formatting, etc) also get alternating colours. So rather, I'd define in my css an entirely new class:
.row-striped:nth-of-type(odd){
background-color: #efefef;
}
.row-striped:nth-of-type(even){
background-color: #ffffff;
}
So now, the alternating row colours will only apply to the row container, when I specify its class as .row-striped
, and not the elements inside the row
.
<!-- this entire row container is #efefef -->
<div class="row row-striped">
<div class="form-group">
<div class="col-sm-8"><h5>Field Greens with strawberry vinegrette</h5></div>
<div class="col-sm-4">
<input type="number" type="number" step="1" min="0"></input><small>$30/salad</small>
</div>
</div>
</div>
<!-- this entire row container is #ffffff -->
<div class="row row-striped">
<div class="form-group">
<div class="col-sm-8"><h5>Greek Salad</h5></div>
<div class="col-sm-4">
<input type="number" type="number" step="1" min="0"></input><small>$25/salad</small>
</div>
</div>
</div>