Found amazing simple solution - working for Chrome (Windows, not tested on Mac)
Zebra ZP 450
This way you will be able to send ZPL to a printer no matter how it is connected (LPT, USB, Network Share...)
Create the RawPrinterHelper class (from the Microsoft article on How to send raw data to a printer by using Visual C# .NET):
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
public class RawPrinterHelper
{
// Structure and API declarions:
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public class DOCINFOA
{
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
}
[DllImport("winspool.Drv", EntryPoint="OpenPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
[DllImport("winspool.Drv", EntryPoint="ClosePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool ClosePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartDocPrinterA", SetLastError=true, CharSet=CharSet.Ansi, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartDocPrinter( IntPtr hPrinter, Int32 level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
[DllImport("winspool.Drv", EntryPoint="EndDocPrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndDocPrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="StartPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool StartPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="EndPagePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool EndPagePrinter(IntPtr hPrinter);
[DllImport("winspool.Drv", EntryPoint="WritePrinter", SetLastError=true, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten );
// SendBytesToPrinter()
// When the function is given a printer name and an unmanaged array
// of bytes, the function sends those bytes to the print queue.
// Returns true on success, false on failure.
public static bool SendBytesToPrinter( string szPrinterName, IntPtr pBytes, Int32 dwCount)
{
Int32 dwError = 0, dwWritten = 0;
IntPtr hPrinter = new IntPtr(0);
DOCINFOA di = new DOCINFOA();
bool bSuccess = false; // Assume failure unless you specifically succeed.
di.pDocName = "My C#.NET RAW Document";
di.pDataType = "RAW";
// Open the printer.
if( OpenPrinter( szPrinterName.Normalize(), out hPrinter, IntPtr.Zero ) )
{
// Start a document.
if( StartDocPrinter(hPrinter, 1, di) )
{
// Start a page.
if( StartPagePrinter(hPrinter) )
{
// Write your bytes.
bSuccess = WritePrinter(hPrinter, pBytes, dwCount, out dwWritten);
EndPagePrinter(hPrinter);
}
EndDocPrinter(hPrinter);
}
ClosePrinter(hPrinter);
}
// If you did not succeed, GetLastError may give more information
// about why not.
if( bSuccess == false )
{
dwError = Marshal.GetLastWin32Error();
}
return bSuccess;
}
public static bool SendFileToPrinter( string szPrinterName, string szFileName )
{
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open);
// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);
// Dim an array of bytes big enough to hold the file's contents.
Byte []bytes = new Byte[fs.Length];
bool bSuccess = false;
// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);
// Read the contents of the file into the array.
bytes = br.ReadBytes( nLength );
// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);
// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);
// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);
// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;
}
public static bool SendStringToPrinter( string szPrinterName, string szString )
{
IntPtr pBytes;
Int32 dwCount;
// How many characters are in the string?
dwCount = szString.Length;
// Assume that the printer is expecting ANSI text, and then convert
// the string to ANSI text.
pBytes = Marshal.StringToCoTaskMemAnsi(szString);
// Send the converted ANSI string to the printer.
SendBytesToPrinter(szPrinterName, pBytes, dwCount);
Marshal.FreeCoTaskMem(pBytes);
return true;
}
}
Call the print method:
private void BtnPrint_Click(object sender, System.EventArgs e)
{
string s = "^XA^LH30,30\n^FO20,10^ADN,90,50^AD^FDHello World^FS\n^XZ";
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new PrinterSettings();
if(DialogResult.OK == pd.ShowDialog(this))
{
RawPrinterHelper.SendStringToPrinter(pd.PrinterSettings.PrinterName, s);
}
}
There are 2 gotchas I've come across that happen when you're sending txt files with ZPL codes to the printer:
Encoding has to be set to Encoding.Default when reading ANSI txt files with special characters
public static bool SendTextFileToPrinter(string szFileName, string printerName)
{
var sb = new StringBuilder();
using (var sr = new StreamReader(szFileName, Encoding.Default))
{
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine());
}
}
return RawPrinterHelper.SendStringToPrinter(printerName, sb.ToString());
}
I understand you want to download an older version via the BitBucket web interface without using a Mercurial/Git client.
Check this related question. On the comments, someone says that there is no way to do that. Fortunately, that's not entirely true.
By navigating on BitBucket project pages, I found no link to download an arbitrary version. There are links to download specific tags, in the format:
https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz
But by tweaking a bit the url above, changing the tag name by the commit hash, like:
https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz
You can actually download a specific version.
As mentioned by Rakka Rage in a comment, replacing .tar.gz
by .zip
works too.
This was tested on Windows XP SP3 and Windows 7 and uses CScript. I put in some safe guards to avoid del "" prompting. (/q
would be dangerous)
Wait one second:
sleepOrDelayExecution 1000
Wait 500 ms and then run stuff after:
sleepOrDelayExecution 500 dir \ /s
@echo off
if "%1" == "" goto end
if NOT %1 GTR 0 goto end
setlocal
set sleepfn="%temp%\sleep%random%.vbs"
echo WScript.Sleep(%1) >%sleepfn%
if NOT %sleepfn% == "" if NOT EXIST %sleepfn% goto end
cscript %sleepfn% >nul
if NOT %sleepfn% == "" if EXIST %sleepfn% del %sleepfn%
for /f "usebackq tokens=1*" %%i in (`echo %*`) DO @ set params=%%j
%params%
:end
I know it's a bit late in the game, but I remembered this question from when it was new and I had a similar dillemma, and I accidently found the "right" solution, if anyone is still looking for one:
<path
d="
M cx cy
m -r, 0
a r,r 0 1,0 (r * 2),0
a r,r 0 1,0 -(r * 2),0
"
/>
In other words, this:
<circle cx="100" cy="100" r="75" />
can be achieved as a path with this:
<path
d="
M 100, 100
m -75, 0
a 75,75 0 1,0 150,0
a 75,75 0 1,0 -150,0
"
/>
The trick is to have two arcs, the second one picking up where the first left off and using the negative diameter to get back to the original arc start point.
The reason it can't be done as a full circle in one arc (and I'm just speculating) is because you would be telling it to draw an arc from itself (let's say 150,150) to itself (150,150), which it renders as "oh, I'm already there, no arc necessary!".
The benefits of the solution I'm offering are:
None of this would matter if they would just allow textpaths to accept shapes. But I think they are avoiding that solution since shape elements like circle don't technically have a "start" point.
jsfiddle demo: http://jsfiddle.net/crazytonyi/mNt2g/
If you are using the path for a textPath
reference and you are wanting the text to render on the outer edge of the arc, you would use the exact same method but change the sweep-flag from 0 to 1 so that it treats the outside of the path as the surface instead of the inside (think of 1,0
as someone sitting at the center and drawing a circle around themselves, while 1,1
as someone walking around the center at radius distance and dragging their chalk beside them, if that's any help). Here is the code as above but with the change:
<path
d="
M cx cy
m -r, 0
a r,r 0 1,1 (r * 2),0
a r,r 0 1,1 -(r * 2),0
"
/>
please try adding this meta-tag and style
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>
<style>
body{
touch-action: manipulation;
}
</style>
If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
If you happen to have php 7.0+ you could use levels.
dirname( __FILE__, 2 )
with the second parameter you can define the amount of levels you want to go back.
try this:
grep -P '^(tomcat!?)' tst1.txt
It will search for specific word in txt file. Here we are trying to search word tomcat
You can redirect the output of a cmd prompt to a file using >
or >>
to append to a file.
i.e.
echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt
or
mybatchfile.bat >C:\output.txt
Note that using >
will automatically overwrite the file if it already exists.
You also have the option of redirecting stdin, stdout and stderr.
See here for a complete list of options.
I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the pagefile size, as it was a Memory overcommitment problem for me too.
Windows 8
Windows 10
Note: I did not have the enough memory on my system for the ~282GB in this example but for my particular case this worked.
EDIT
From here the suggested recommendations for page file size:
There is a formula for calculating the correct pagefile size. Initial size is one and a half (1.5) x the amount of total system memory. Maximum size is three (3) x the initial size. So let's say you have 4 GB (1 GB = 1,024 MB x 4 = 4,096 MB) of memory. The initial size would be 1.5 x 4,096 = 6,144 MB and the maximum size would be 3 x 6,144 = 18,432 MB.
Some things to keep in mind from here:
However, this does not take into consideration other important factors and system settings that may be unique to your computer. Again, let Windows choose what to use instead of relying on some arbitrary formula that worked on a different computer.
Also:
Increasing page file size may help prevent instabilities and crashing in Windows. However, a hard drive read/write times are much slower than what they would be if the data were in your computer memory. Having a larger page file is going to add extra work for your hard drive, causing everything else to run slower. Page file size should only be increased when encountering out-of-memory errors, and only as a temporary fix. A better solution is to adding more memory to the computer.
In my case it was Bootstrap popup in opened state.
Text input was in another calendar popup on top of Bootstrap one, input got its focus back after removing tabindex="-1"
attribute from Bootstrap modal.
The following can be used to get the date:
function date_date() {
var date = new Date();
var year = date.getYear();
var month = date.getMonth() + 1; if(month.toString().length==1){var month =
'0'+month;}
var day = date.getDate(); if(day.toString().length==1){var day = '0'+day;}
var hour = date.getHours(); if(hour.toString().length==1){var hour = '0'+hour;}
var minu = date.getMinutes(); if(minu.toString().length==1){var minu = '0'+minu;}
var seco = date.getSeconds(); if(seco.toString().length==1){var seco = '0'+seco;}
var date = year+'·'+month+'·'+day+'·'+hour+'·'+minu+'·'+seco;
Logger.log(date);
}
Try
Also, you can just set the ViewName:
return View("ViewName");
Full controller example:
public ActionResult SomeAction() {
if (condition)
{
return View("CustomView");
}else{
return View();
}
}
This works on MVC 5.
Considering that we have Set<String> stringSet
we can use following:
List<String> strList = new ArrayList<>(stringSet);
List<String> strList = Lists.newArrayList(stringSet);
List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);
List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());
import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());
As per the doc for the method toList()
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).
So if we need a specific implementation e.g. ArrayList
we can get it this way:
List<String> stringList2 = stringSet.stream().
collect(toCollection(ArrayList::new));
We can make use of Collections::unmodifiableList
method and wrap the list returned in previous examples. We can also write our own custom method as:
class ImmutableCollector {
public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
return Collector.of( supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
}
And then use it as:
List<String> stringList3 = stringSet.stream()
.collect(ImmutableCollector.toImmutableList(ArrayList::new));
Another possibility is to make use of collectingAndThen
method which allows some final transformation to be done before returning result:
List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
toCollection(ArrayList::new),Collections::unmodifiableList));
One point to note is that the method Collections::unmodifiableList
returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList
returns truly immutable list in Java 10.
We managed to get this working exactly as described in the OP, and hopefully someone else can make use of the solution. Here's what we did:
Set up the security context like so:
<security:http realm="Protected API" use-expressions="true" auto-config="false" create-session="stateless" entry-point-ref="CustomAuthenticationEntryPoint">
<security:custom-filter ref="authenticationTokenProcessingFilter" position="FORM_LOGIN_FILTER" />
<security:intercept-url pattern="/authenticate" access="permitAll"/>
<security:intercept-url pattern="/**" access="isAuthenticated()" />
</security:http>
<bean id="CustomAuthenticationEntryPoint"
class="com.demo.api.support.spring.CustomAuthenticationEntryPoint" />
<bean id="authenticationTokenProcessingFilter"
class="com.demo.api.support.spring.AuthenticationTokenProcessingFilter" >
<constructor-arg ref="authenticationManager" />
</bean>
As you can see, we've created a custom AuthenticationEntryPoint
, which basically just returns a 401 Unauthorized
if the request wasn't authenticated in the filter chain by our AuthenticationTokenProcessingFilter
.
CustomAuthenticationEntryPoint:
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
}
}
AuthenticationTokenProcessingFilter:
public class AuthenticationTokenProcessingFilter extends GenericFilterBean {
@Autowired UserService userService;
@Autowired TokenUtils tokenUtils;
AuthenticationManager authManager;
public AuthenticationTokenProcessingFilter(AuthenticationManager authManager) {
this.authManager = authManager;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
@SuppressWarnings("unchecked")
Map<String, String[]> parms = request.getParameterMap();
if(parms.containsKey("token")) {
String token = parms.get("token")[0]; // grab the first "token" parameter
// validate the token
if (tokenUtils.validate(token)) {
// determine the user based on the (already validated) token
UserDetails userDetails = tokenUtils.getUserFromToken(token);
// build an Authentication object with the user's info
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
// set the authentication into the SecurityContext
SecurityContextHolder.getContext().setAuthentication(authManager.authenticate(authentication));
}
}
// continue thru the filter chain
chain.doFilter(request, response);
}
}
Obviously, TokenUtils
contains some privy (and very case-specific) code and can't be readily shared. Here's its interface:
public interface TokenUtils {
String getToken(UserDetails userDetails);
String getToken(UserDetails userDetails, Long expiration);
boolean validate(String token);
UserDetails getUserFromToken(String token);
}
That ought to get you off to a good start. Happy coding. :)
For people looking to do if statements with multiple 'or' values.
<div ng-if="::(a || b || c || d || e || f)"><div>
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?
I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new
, fill the object in with the data, and then push the address of the data onto the vector
(probably not the best design, but most likely what's intended anyway).
<a href="mailto:[email protected]?subject=Request&body=Hi,%0DName:[your name] %0DGood day " target="_blank"></a>
Try adding %0D to break the line. This will definitely work.
Above code will display the following:
Hi,
Name:[your name]
Good day
What about:
char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;
copying to e to preserve the original string, I suppose if you don't care you could just operate over *string
To all who are using split, slice and other string-based attempts to obtain the date, you might set yourself up for timezone related fails!
An ISO-String has Zulu-Timezone and a date according to this timezone, which means, it might use a date a day prior or later to the actual timezone, which you have to take into account in your transformation chain.
See this example:
const timeZoneRelatedDate = new Date(2020, 0, 14, 0, 0);
console.log(timeZoneRelatedDate.toLocaleDateString(
'ja-JP',
{
year: 'numeric',
month: '2-digit',
day: '2-digit'
}
).replace(/\//gi,'-'));
// RESULT: "2020-01-14"
console.log(timeZoneRelatedDate.toISOString());
// RESULT: "2020-01-13T23:00:00.000Z" (for me in UTC+1)
console.log(timeZoneRelatedDate.toISOString().slice(0,10));
// RESULT: "2020-01-13"
import curses
stdscr = curses.initscr()
stdscr.clear()
How can I display these open transactions and commit or cancel them?
There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).
You display threads using
SHOW FULL PROCESSLIST
See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html
It will not help you, because you cannot commit a transaction from a broken connection.
What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html
4.5.1.6.3. Disabling mysql Auto-Reconnect
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.
This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
How to diagnose and fix this
To check for auto-reconnection:
If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call
mysql_thread_id()
to get the original connection identifier before callingmysql_ping()
, then callmysql_thread_id()
again to see whether the identifier has changed.
Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.
I would try to set a flag on the window.onfocus
and window.onblur
events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.
here is the example using Pure JavaScript
function scrollpage() { _x000D_
function f() _x000D_
{_x000D_
window.scrollTo(0,i);_x000D_
if(status==0) {_x000D_
i=i+40;_x000D_
if(i>=Height){ status=1; } _x000D_
} else {_x000D_
i=i-40;_x000D_
if(i<=1){ status=0; } // if you don't want continue scroll then remove this line_x000D_
}_x000D_
setTimeout( f, 0.01 );_x000D_
}f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
#top { border: 1px solid black; height: 20000px; }_x000D_
#bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
The getRequestURL()
omits the port when it is 80 while the scheme is http
, or when it is 443 while the scheme is https
.
So, just use getRequestURL()
if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:
StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();
You can allow database access on the main thread but only for debugging purpose, you shouldn't do this on production.
Note: Room doesn't support database access on the main thread unless you've called allowMainThreadQueries() on the builder because it might lock the UI for a long period of time. Asynchronous queries—queries that return instances of LiveData or Flowable—are exempt from this rule because they asynchronously run the query on a background thread when needed.
Here is an example ...
select * from tablename where to_char(added_time, 'YYYY-MM-DD') = to_char( now(), 'YYYY-MM-DD' )
added_time is a column name which I converted to char for match
em is the typography unit of font width. one em in a 16-point typeface is 16 points
As android:editable=""
is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only".
However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
I've solve the issue. The solution is to not making virtual dir manualy and then copy app files here, but use 'Add Application...' option. Here is post that helped me http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/7ad2acb0-42ca-4ee8-9161-681689b60dda/
Also you can try to use
display:inline-block;
if you would like the span element to align horizontally.
Incase you would like to align span elements vertically, just use
display:block;
Try "sudo mysql -u root -p" please.
You want to convert it to an object first and then access normally making sure to cast it.
JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];
You can simply set xhr.responseType = 'json';
const xhr = new XMLHttpRequest();_x000D_
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/1');_x000D_
xhr.responseType = 'json';_x000D_
xhr.onload = function(e) {_x000D_
if (this.status == 200) {_x000D_
console.log('response', this.response); // JSON response _x000D_
}_x000D_
};_x000D_
xhr.send();_x000D_
_x000D_
Try the below code-
mSQLiteDatabase = getWritableDatabase();//To delete , database should be writable.
int rowDeleted = mSQLiteDatabase.delete(TABLE_NAME,id + " =?",
new String[] {String.valueOf(id)});
mSQLiteDatabase.close();//This is very important once database operation is done.
if(rowDeleted != 0){
//delete success.
} else {
//delete failed.
}
If you are using responsive layout, try including this js on your code: https://github.com/scottjehl/Respond
I had the same problem as the current .NET SDK does not support targeting .NET Core 3.1. Either target .NET Core 1.1 or lower, or use a version of the .NET SDK that supports .NET Core 3.1
1) Make sure .Net core SDK installed on your machine. Download .NET!
2) set PATH environment variables as below Path
As you have given static text
err.setText("Escriba su mensaje y luego seleccione el canal.");
It will not change , it will remain same.
Example for Dynamic Text for textview is :
MainActivity.java
package com.example.dynamictextview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
int count = 0;
Button clickMeBtn;
TextView dynamicText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clickMeBtn = (Button) findViewById(R.id.button_click);
dynamicText = (TextView) findViewById(R.id.textview);
clickMeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
count++;
dynamicText.setText("dynamic text example : " + count);
}
});
}
}
For activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.dynamictextview.MainActivity" >
<Button
android:id="@+id/button_click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click me"
android:layout_centerInParent="true" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:layout_below="@id/button_click"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:layout_marginTop="20dp"
/>
</RelativeLayout>
Three things need to care for:
It indicates that the servlet won't be started until a request tries to access it.
If load-on-startup is greater than or equal to zero then when the container starts it will start that servlet in ascending order of the load on startup value you put there (ie 0, 1 then 2 then 5 then 10 and so on).
It's simple. On the sender side, use Intent.putExtra
:
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
On the receiver side, use Intent.getIntExtra
:
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intVariableName", 0);
In addition to all the other correct answers, since Rails.root
is a Pathname
object, this won't work:
Rails.root + '/app/assets/...'
You could use something like join
Rails.root.join('app', 'assets')
If you want a string use this:
Rails.root.join('app', 'assets').to_s
You can checkout remote branch /n git fetch && git checkout remotebranch
You need to use the m
flag:
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
Also put the *
in the right place:
"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^ ^
//-----------------------------------------------------------------------|
Had the same issue, in my case the cause was that the web.config file was missing in the virtual dir folder.
This version works well with newlines inside inserts:
sqlite3 database.sqlite3 .dump | grep -v '^CREATE'
In practice excludes all the lines starting with CREATE
which is less likely to contain newlines
You can use the NonNullable
Utility Type:
Example
type T0 = NonNullable<string | number | undefined>; // string | number
type T1 = NonNullable<string[] | null | undefined>; // string[]
Docs.
To simplify Kirubaharan's answer a bit:
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('Datetime')
And to get rid of unwanted columns (as OP did but did not specify per se in the question):
df = df.drop(['date','time'], axis=1)
If we want only hh:mm:ss, we can use a function like that:
//param: duration in milliseconds
MillisecondsToTime: function(duration) {
var seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(1000*60*60))%24)
, days = parseInt(duration/(1000*60*60*24));
var hoursDays = parseInt(days*24);
hours += hoursDays;
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds;
}
Using ASP.Net Post call, this worked for me.
StringBuilder getNewToken = new StringBuilder();
getNewToken.Append("https://www.googleapis.com/oauth2/v4/token");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(getNewToken.ToString());
var values = new Dictionary<string, string>
{
{ "client_id", <Your Client Id> },
{ "client_secret", <Your Client Secret> },
{ "refresh_token", <Your Saved Refresh Token> },
{ "grant_type", "refresh_token"}
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync(getNewToken.ToString(), content);
Using res.json with Express:
function random(response) {
console.log("response.json sets the appropriate header and performs JSON.stringify");
response.json({
anObject: { item1: "item1val", item2: "item2val" },
anArray: ["item1", "item2"],
another: "item"
});
}
Alternatively:
function random(response) {
console.log("Request handler random was called.");
response.writeHead(200, {"Content-Type": "application/json"});
var otherArray = ["item1", "item2"];
var otherObject = { item1: "item1val", item2: "item2val" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: "item"
});
response.end(json);
}
++ This worked for me. It's vanilla javascirpt
and good for use cases such as de-cluttering when testing with ngMocks
library:
<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!-- Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>
This is your javascript
file that contains the JSON
data
// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
"Title": "Star Wars",
"Year": "1983",
"Rated": "N/A",
"Released": "01 May 1983",
"Runtime": "N/A",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "N/A",
"Writer": "N/A",
"Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "N/A",
"Metascore": "N/A",
"imdbRating": "7.9",
"imdbVotes": "342",
"imdbID": "tt0251413",
"Type": "game",
"Response": "True"
};
Finally, work with the JSON data anywhere in your code
// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;
Note:- This is great for testing and even karma.conf.js
accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development
environment.
// extract from karma.conf.js
files: [
'json-data/JSONSearchResultHardcodedData.js',
'json-data/JSONFindByIdResults.js'
...
]
Hope this helps.
++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733
UPDATE
An easier way that worked for me is just include a function
at the bottom of the code returning whatever JSON
.
// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
return {
"Title": "Bri Squared",
"Year": "2011",
"Rated": "N/A",
"Released": "N/A",
"Runtime": "N/A",
"Genre": "Comedy",
"Director": "Joy Gohring",
"Writer": "Briana Lane",
"Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
"Plot": "N/A",
"Language": "English",
"Country": "USA",
"Awards": "N/A",
"Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
"Metascore": "N/A",
"imdbRating": "8.2",
"imdbVotes": "5",
"imdbID": "tt1937109",
"Type": "movie",
"Response": "True"
}
}
Simple solution, make a custom control. (this is made in Xamarin android but should port easily to java)
public class EditTextDecimalNumber:EditText
{
readonly string _numberFormatDecimalSeparator;
public EditTextDecimalNumber(Context context, IAttributeSet attrs) : base(context, attrs)
{
InputType = InputTypes.NumberFlagDecimal;
TextChanged += EditTextDecimalNumber_TextChanged;
_numberFormatDecimalSeparator = System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator;
KeyListener = DigitsKeyListener.GetInstance($"0123456789{_numberFormatDecimalSeparator}");
}
private void EditTextDecimalNumber_TextChanged(object sender, TextChangedEventArgs e)
{
int noOfOccurence = this.Text.Count(x => x.ToString() == _numberFormatDecimalSeparator);
if (noOfOccurence >=2)
{
int lastIndexOf = this.Text.LastIndexOf(_numberFormatDecimalSeparator,StringComparison.CurrentCulture);
if (lastIndexOf!=-1)
{
this.Text = this.Text.Substring(0, lastIndexOf);
this.SetSelection(this.Text.Length);
}
}
}
}
According to your explanation you haven't included your Class2.cs
in your project. You have just created the required Class file but haven't included that in the project.
The Class2.cs was created with [File] -> [New] -> [File] -> [C# class] and saved in the same folder where program.cs lives.
Do the following to overcome this,
Simply Right click
on your project then -> [Add] - > [Existing Item...] : Select Class2.cs
and press OK
Problem should be solved now.
Furthermore, when adding new classes use this procedure,
Right click
on project -> [Add] -> Select Required Item (ex - A class, Form etc.)
You can try this:
NSLog(@"%@", NSStringFromCGPoint(cgPoint));
There are a number of functions provided by UIKit that convert the various CG structs into NSString
s. The reason it doesn't work is because %@
signifies an object. A CGPoint
is a C struct (and so are CGRect
s and CGSize
s).
table{border-collapse:collapse;}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
If you are looking for a scripted solution:
.vsix
files (see example below)unzip
the binary into ~/.vscode/extensions/
: you need to modify unzipped directory name, remove one file and move/rename another one.For API start by looking at following example, and for hints how to modify request head to https://github.com/Microsoft/vscode/blob/master/src/vs/platform/extensionManagement/common/extensionGalleryService.ts.
POST https://marketplace.visualstudio.com/_apis/public/gallery/extensionquery?api-version=5.1-preview HTTP/1.1
content-type: application/json
{
"filters": [
{
"criteria": [
{
"filterType": 8,
"value": "Microsoft.VisualStudio.Code",
},
{
"filterType": 7,
"value": "ms-python.python",
}
],
"pageNumber": 1,
"pageSize": 10,
"sortBy": 0,
"sortOrder": 0,
}
],
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"],
"flags": 514,
}
Explanations to the above example:
"filterType": 8
- FilterType.Target
more FilterTypes"filterType": 7
- FilterType.ExtensionName
more FilterTypes"flags": 514
- 0x2 | 0x200
- Flags.IncludeFiles | Flags.IncludeLatestVersionOnly
- more Flags
python -c "print(0x2|0x200)"
"assetTypes": ["Microsoft.VisualStudio.Services.VSIXPackage"]
- to get only link to .vsix
file more AssetTypesif ($_SERVER['REQUEST_METHOD'] == 'POST')
is the correct way, you can send a post request without any post data.
this worked for me
// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = new PathString("/auth/login");
options.AccessDeniedPath = new PathString("/auth/denied");
});
Try this:
Display display = getWindowManager().getDefaultDisplay();
Point displaySize = new Point();
display.getSize(displaySize);
int width = displaySize.x;
int height = displaySize.y;
fabric
could be used to upload files vis ssh:
#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all
if __name__=="__main__":
import sys
# specify hostname to connect to and the remote/local paths
srcdir, remote_dirname, hostname = sys.argv[1:]
try:
s = execute(put, srcdir, remote_dirname, host=hostname)
print(repr(s))
finally:
disconnect_all()
As a programming noob, I found a bunch of the above answers overly complex, especially if the goal is to have a simple function that you can pass various yes/no questions to, forcing the user to select yes or no. After scouring this page and several others, and borrowing all of the various good ideas, I ended up with the following:
def yes_no(question_to_be_answered):
while True:
choice = input(question_to_be_answered).lower()
if choice[:1] == 'y':
return True
elif choice[:1] == 'n':
return False
else:
print("Please respond with 'Yes' or 'No'\n")
#See it in Practice below
musical_taste = yes_no('Do you like Pine Coladas?')
if musical_taste == True:
print('and getting caught in the rain')
elif musical_taste == False:
print('You clearly have no taste in music')
In the .NET world AOP isn't too popular, so for DI a framework is your only real option, whether you write one yourself or use another framework.
If you used AOP you can inject when you compile your application, which is more common in Java.
There are many benefits to DI, such as reduced coupling so unit testing is easier, but how will you implement it? Do you want to use reflection to do it yourself?
You can place your tables in a div and add style to your table "float: left"
<div>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
<table style="float: left">
<tr>
<td>..</td>
</tr>
</table>
</div>
or simply use css:
div>table {
float: left
}
The following bit of code does what you ask for. Just make sure that you assign enough space so that the text on the button becomes visible
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4,4,4,4));
for(int i=0 ; i<16 ; i++){
JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
panel.add(btn);
}
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
The X and Y (two first parameters of the GridLayout constructor) specify the number of rows and columns in the grid (respectively). You may leave one of them as 0 if you want that value to be unbounded.
Edit
I've modified the provided code and I believe it now conforms to what is desired:
JFrame frame = new JFrame("Colored Trails");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(4, 4));
firstPanel.setMaximumSize(new Dimension(400, 400));
JButton btn;
for (int i=1; i<=4; i++) {
for (int j=1; j<=4; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(100, 100));
firstPanel.add(btn);
}
}
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new GridLayout(5, 13));
secondPanel.setMaximumSize(new Dimension(520, 200));
for (int i=1; i<=5; i++) {
for (int j=1; j<=13; j++) {
btn = new JButton();
btn.setPreferredSize(new Dimension(40, 40));
secondPanel.add(btn);
}
}
mainPanel.add(firstPanel);
mainPanel.add(secondPanel);
frame.setContentPane(mainPanel);
frame.setSize(520,600);
frame.setMinimumSize(new Dimension(520,600));
frame.setVisible(true);
Basically I now set the preferred size of the panels and a minimum size for the frame.
Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.
For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.
Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help()
function available in the interactive interpreter.
document.getElementById("address_box").value =
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
Let me suggest you an easier approach,
Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;
Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.
Copy these two files into a text editor. Checkout master. Paste the files. Commit.
That simple.
You can use SublimeREPL (you need to have Package Control installed first).
The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.
mvnw: it's an executable Unix shell script used in place of a fully installed Maven
mvnw.cmd: it's for Windows environment
Use Cases
The wrapper should work with different operating systems such as:
After that, we can run our goals like this for the Unix system:
./mvnw clean install
And the following command for Batch:
./mvnw.cmd clean install
If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists
of the system.
Maven Wrapper plugin
Maven Wrapper plugin to make auto installation in a simple Spring Boot project.
First, we need to go in the main folder of the project and run this command:
mvn -N io.takari:maven:wrapper
We can also specify the version of Maven:
mvn -N io.takari:maven:wrapper -Dmaven=3.5.2
The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.
Source 1 (further reading): https://www.baeldung.com/maven-wrapper
ugh don't use eval for anything. Well, there are certain things, but they're extremely rare. Rather, you would do this:
document.getElementById("test").onchange()
Look here for more options: http://jehiah.cz/archive/firing-javascript-events-properly
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
I tried:
<input id="btnTest" type="button" value="button" />
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
and C#:
[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
return Content(ListID + " " + ItemName);
}
It worked. Remove contentType
and set data
without double quotes.
An other simply way:
var fn = function () {}
if (fn.constructor === Function) {
// true
} else {
// false
}
As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...
using System.Diagnostics;
...
Process.Start("process.exe");
The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.
using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.
This method allows far more control than I've mentioned.
Your .gitignore
is working, but it still tracks the files because they were already in the index.
To stop this you have to do : git rm -r --cached .idea/
When you commit the .idea/
directory will be removed from your git repository and the following commits will ignore the .idea/
directory.
PS: You could use .idea/
instead of .idea/*
to ignore a directory. You can find more info about the patterns on the .gitignore man page.
Helpful quote from the git-rm
man page
--cached
Use this option to unstage and remove paths only from the index.
Working tree files, whether modified or not, will be left alone.
If you have a usual pointer (A*
) then the destructor will not be called (and memory for A
instance will not be freed either) unless you do delete
explicitly in B
's destructor. If you want automatic destruction look at smart pointers like auto_ptr
.
#!/bin/bash
#file getActivity.sh
package_name=$1
#launch app by package name
adb shell monkey -p ${package_name} -c android.intent.category.LAUNCHER 1;
sleep 1;
#get Activity name
adb shell logcat -d | grep 'START u0' | tail -n 1 | sed 's/.*cmp=\(.*\)} .*/\1/g'
sample:
getActivity.sh com.tencent.mm
com.tencent.mm/.ui.LauncherUI
If you have the file my-default.ini
rename it to my.ini
I have one generic log4j.xml file for you:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<appender name="default.console" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="default.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/mylogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="another.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/anotherlogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<logger name="com.yourcompany.SomeClass" additivity="false">
<level value="debug" />
<appender-ref ref="another.file" />
</logger>
<root>
<priority value="info" />
<appender-ref ref="default.console" />
<appender-ref ref="default.file" />
</root>
</log4j:configuration>
with one console, two file appender and one logger poiting to the second file appender instead of the first.
EDIT
In one of the older projects I have found a simple log4j.properties file:
# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.
# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file
# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n
log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n
For the description of all the layout arguments look here: log4j PatternLayout arguments
The error is because fName
is included in the SELECT
list, but is not included in a GROUP BY
clause and is not part of an aggregate function (Count()
, Min()
, Max()
, Sum()
, etc.)
You can fix that problem by including fName
in a GROUP BY
. But then you will face the same issue with surname
. So put both in the GROUP BY
:
SELECT
fName,
surname,
Count(*) AS num_rows
FROM
author
INNER JOIN book
ON author.aID = book.authorID;
GROUP BY
fName,
surname
Note I used Count(*)
where you wanted SUM(orders.quantity)
. However, orders
isn't included in the FROM
section of your query, so you must include it before you can Sum()
one of its fields.
If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.
I just used ExcelLibrary to load an .xls spreadsheet into a DataSet. Worked great for me.
In Windows, capitalization in paths doesn't matter. In Linux it does.
When you autoload, use "Foo" not "foo".
I believe that will do the trick.
I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.
I'm forced to post this as an answer instead of a comment due to low reputation.
I had a similar problem to Matteo. The difference being that I had no map from my first x-axis to my second x-axis, only the x-values themselves. So I wanted to set the data on my second x-axis directly, not the ticks, however, there is no axes.set_xdata
. I was able to use Dhara's answer to do this with a modification:
ax2.lines = []
instead of using:
ax2.cla()
When in use also cleared my plot from ax1
.
In your CSS stylesheet, try adding:
input[type="text"] {
font-size:25px;
}
See this jsFiddle example
Today, I have used this feature, so here's my very fresh real-life example. (I have changed class and method names to generic ones so they won't distract from the actual point.)
I have a method that's meant to accept a Set
of A
objects that I originally wrote with this signature:
void myMethod(Set<A> set)
But it want to actually call it with Set
s of subclasses of A
. But this is not allowed! (The reason for that is, myMethod
could add objects to set
that are of type A
, but not of the subtype that set
's objects are declared to be at the caller's site. So this could break the type system if it were possible.)
Now here come generics to the rescue, because it works as intended if I use this method signature instead:
<T extends A> void myMethod(Set<T> set)
or shorter, if you don't need to use the actual type in the method body:
void myMethod(Set<? extends A> set)
This way, set
's type becomes a collection of objects of the actual subtype of A
, so it becomes possible to use this with subclasses without endangering the type system.
In your php.ini
configuration file simply uncomment the extension:
;extension=pdo_mysql
(You can find your php.ini file in the php folder where your server is installed.)
make this to
extension=pdo_mysql
now you need to configure your .env file in find DB_DATABASE=
write in that database name which you used than migrate like if i used my database and database name is "abc" than i need to write there DB_DATABASE=abc
and save that .env file and run command again
php artisan migrate
so after run than you got some msg like as:
php artisan migrate
Migration table created successfully.
For Windows, you can run this command directly if mysql/bin is in your path.
mysqladmin -u root -p shutdown
You need to declare timer
outside the function. Otherwise, you get a brand new variable on each function invocation.
var timer;
function endAndStartTimer() {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
Just some notes on timing:
If you're starting with a list, l.append(l.pop(0))
is the fastest method you can use. This can be shown with time complexity alone:
So if you are starting with deque
objects, you can deque.rotate()
at the cost of O(k). But, if the starting point is a list, the time complexity of using deque.rotate()
is O(n). l.append(l.pop(0)
is faster at O(1).
Just for the sake of illustration, here are some sample timings on 1M iterations:
Methods which require type conversion:
deque.rotate
with deque object: 0.12380790710449219 seconds (fastest)deque.rotate
with type conversion: 6.853878974914551 secondsnp.roll
with nparray: 6.0491721630096436 secondsnp.roll
with type conversion: 27.558452129364014 secondsList methods mentioned here:
l.append(l.pop(0))
: 0.32483696937561035 seconds (fastest)shiftInPlace
": 4.819645881652832 secondsTiming code used is below.
Showing that creating deques from lists is O(n):
from collections import deque
import big_o
def create_deque_from_list(l):
return deque(l)
best, others = big_o.big_o(create_deque_from_list, lambda n: big_o.datagen.integers(n, -100, 100))
print best
# --> Linear: time = -2.6E-05 + 1.8E-08*n
If you need to create deque objects:
1M iterations @ 6.853878974914551 seconds
setup_deque_rotate_with_create_deque = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
"""
test_deque_rotate_with_create_deque = """
dl = deque(l)
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_with_create_deque, setup_deque_rotate_with_create_deque)
If you already have deque objects:
1M iterations @ 0.12380790710449219 seconds
setup_deque_rotate_alone = """
from collections import deque
import random
l = [random.random() for i in range(1000)]
dl = deque(l)
"""
test_deque_rotate_alone= """
dl.rotate(-1)
"""
timeit.timeit(test_deque_rotate_alone, setup_deque_rotate_alone)
If you need to create nparrays
1M iterations @ 27.558452129364014 seconds
setup_np_roll_with_create_npa = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
"""
test_np_roll_with_create_npa = """
np.roll(l,-1) # implicit conversion of l to np.nparray
"""
If you already have nparrays:
1M iterations @ 6.0491721630096436 seconds
setup_np_roll_alone = """
import numpy as np
import random
l = [random.random() for i in range(1000)]
npa = np.array(l)
"""
test_roll_alone = """
np.roll(npa,-1)
"""
timeit.timeit(test_roll_alone, setup_np_roll_alone)
Requires no type conversion
1M iterations @ 4.819645881652832 seconds
setup_shift_in_place="""
import random
l = [random.random() for i in range(1000)]
def shiftInPlace(l, n):
n = n % len(l)
head = l[:n]
l[:n] = []
l.extend(head)
return l
"""
test_shift_in_place="""
shiftInPlace(l,-1)
"""
timeit.timeit(test_shift_in_place, setup_shift_in_place)
Requires no type conversion
1M iterations @ 0.32483696937561035
setup_append_pop="""
import random
l = [random.random() for i in range(1000)]
"""
test_append_pop="""
l.append(l.pop(0))
"""
timeit.timeit(test_append_pop, setup_append_pop)
for use sample touch listener just you need this code
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
view.startDrag(data, shadowBuilder, null, 0);
return true;
}
Use Convert.ToInt32() for conversion. You can have a look at How to convert string to ASCII value in C# and ASCII values.
In the case where item
and z
are sorted iterators, we can reduce the complexity from O(n^2)
to O(n+m)
by doing this
def iexclude(sorted_iterator, exclude_sorted_iterator):
next_val = next(exclude_sorted_iterator)
for item in sorted_iterator:
try:
while next_val < item:
next_val = next(exclude_sorted_iterator)
continue
if item == next_val:
continue
except StopIteration:
pass
yield item
If the two are iterators, we also have the opportunity to reduce the memory footprint not storing z
(exclude_sorted_iterator
) as a list.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
filenames = '000'.upto('100').map { |index| "file_#{index}" }
Outputs
[file_000, file_001, file_002, file_003, ..., file_098, file_099, file_100]
og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"
console.log(og_date.split('-')); // => [ '2012', '10', '01' ]
og_date.value
would only work if the date were stored as a property on the og_date object.
Such as: var og_date = {}; og_date.value="2012-10-01";
In that case, your original console.log would work.
You will probably load the os module anyway, so another suggestion would be:
import os
myhost = os.uname()[1]
Just adding my answer for the case where there are multiple versions of PHP installed in your system, and you are sure that you have already installed the php-curl
package, and yet Apache is still giving you the same error.
Here are many solutions :
To upercaser with perl, tr, sed and awk
perl -ne 'print uc'
perl -npe '$_=uc'
perl -npe 'tr/[a-z]/[A-Z]/'
perl -npe 'tr/a-z/A-Z/'
tr '[a-z]' '[A-Z]'
sed y/abcdefghijklmnopqrstuvwxyz/ABCDEFGHIJKLMNOPQRSTUVWXYZ/
sed 's/\([a-z]\)/\U\1/g'
sed 's/.*/\U&/'
awk '{print toupper($0)}'
To lowercase with perl, tr, sed and awk
perl -ne 'print lc'
perl -npe '$_=lc'
perl -npe 'tr/[A-Z]/[a-z]/'
perl -npe 'tr/A-Z/a-z/'
tr '[A-Z]' '[a-z]'
sed y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
sed 's/\([A-Z]\)/\L\1/g'
sed 's/.*/\L&/'
awk '{print tolower($0)}'
Complicated bash to lowercase :
while read v;do v=${v//A/a};v=${v//B/b};v=${v//C/c};v=${v//D/d};v=${v//E/e};v=${v//F/f};v=${v//G/g};v=${v//H/h};v=${v//I/i};v=${v//J/j};v=${v//K/k};v=${v//L/l};v=${v//M/m};v=${v//N/n};v=${v//O/o};v=${v//P/p};v=${v//Q/q};v=${v//R/r};v=${v//S/s};v=${v//T/t};v=${v//U/u};v=${v//V/v};v=${v//W/w};v=${v//X/x};v=${v//Y/y};v=${v//Z/z};echo "$v";done
Complicated bash to uppercase :
while read v;do v=${v//a/A};v=${v//b/B};v=${v//c/C};v=${v//d/D};v=${v//e/E};v=${v//f/F};v=${v//g/G};v=${v//h/H};v=${v//i/I};v=${v//j/J};v=${v//k/K};v=${v//l/L};v=${v//m/M};v=${v//n/N};v=${v//o/O};v=${v//p/P};v=${v//q/Q};v=${v//r/R};v=${v//s/S};v=${v//t/T};v=${v//u/U};v=${v//v/V};v=${v//w/W};v=${v//x/X};v=${v//y/Y};v=${v//z/Z};echo "$v";done
Simple bash to lowercase :
while read v;do echo "${v,,}"; done
Simple bash to uppercase :
while read v;do echo "${v^^}"; done
Note that ${v,} and ${v^} only change the first letter.
You should use it that way :
(while read v;do echo "${v,,}"; done) < input_file.txt > output_file.txt
You can convert it to a timedelta with a day precision. To extract the integer value of days you divide it with a timedelta of one day.
>>> x = np.timedelta64(2069211000000000, 'ns')
>>> days = x.astype('timedelta64[D]')
>>> days / np.timedelta64(1, 'D')
23
Or, as @PhillipCloud suggested, just days.astype(int)
since the timedelta
is just a 64bit integer that is interpreted in various ways depending on the second parameter you passed in ('D'
, 'ns'
, ...).
You can find more about it here.
If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..
Had the same issue and was getting the same error. When i ran xcode-select -p
, it gave output as /Library/Developer/CommandLineTools
. So that means xcode was already installed in my system. Then i ran steps as given on this answer. After which any command which required xcode ran successfully.
You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
My way of implementation in Swift...
ConfigurationManager.swift
import Foundation
let ConfigurationManagerSharedInstance = ConfigurationManager()
class ConfigurationManager : NSObject {
var globalDic: NSMutableDictionary = NSMutableDictionary()
class var sharedInstance:ConfigurationManager {
return ConfigurationManagerSharedInstance
}
init() {
super.init()
println ("Config Init been Initiated, this will be called only onece irrespective of many calls")
}
Access the globalDic from any screen of the application by the below.
Read:
println(ConfigurationManager.sharedInstance.globalDic)
Write:
ConfigurationManager.sharedInstance.globalDic = tmpDic // tmpDict is any value that to be shared among the application
Call the continuation with TaskScheduler.FromCurrentSynchronizationContext()
:
Task UITask= task.ContinueWith(() =>
{
this.TextBlock1.Text = "Complete";
}, TaskScheduler.FromCurrentSynchronizationContext());
This is suitable only if the current execution context is on the UI thread.
In some cases we could have a couple of tables, and then we need to detect click just for particular table. My solution is this:
<table id="elitable" border="1" cellspacing="0" width="100%">
<tr>
<td>100</td><td>AAA</td><td>aaa</td>
</tr>
<tr>
<td>200</td><td>BBB</td><td>bbb</td>
</tr>
<tr>
<td>300</td><td>CCC</td><td>ccc</td>
</tr>
</table>
<script>
$(function(){
$("#elitable tr").click(function(){
alert (this.rowIndex);
});
});
</script>
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
Based on my experience, the numpy docstring conventions (PEP257 superset) are the most widely-spread followed conventions that are also supported by tools, such as Sphinx.
One example:
Parameters
----------
x : type
Description of parameter `x`.
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation
).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
I had the same problem, but this worked for me:
<a ng-href="javascript:void(0);#tagId"></a>
Most answers talks about constructing std::string
.
If already constructed, just use assignment operator.
std::string oString;
char* pStr;
... // Here allocate and get character string (e.g. using fgets as you mentioned)
oString = pStr; // This is it! It copies contents from pStr to oString
Try using FLAG_ACTIVITY_CLEAR_TASK
solution with fontawesome
#polyNedir ul li { position:relative;padding-left:20px }
#polyNedir ul li:after{font-family:fontawesome;content:'\f111';position:absolute;left:0px;top:3px;color:#fff;font-size:10px;}
The following code did it for me to make a shadow inset of the right side:
-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;
Hope it will help!!!!
You can use html
instead of text
and replace each occurrence of \n
with <br>
. You will have to correctly escape your text though.
x = x.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/\n/g, '<br>');
you have to use bash instead or rewrite your script using standard sh
sh -c 'test "$choose" = "y" -o "$choose" = "Y"'
After going through all the solutions here, the easiest way to find the loaded php.ini
file is to go into phpinfo
on the loaded MAMP webpage, which will show you the loaded php.ini file.
This will also confirm if the parameters you change, like max_file_size, have updated correctly.
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);
Or if you're sure there won't be any other digits in the string:
var str = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);
There is no difference between keystore and truststore files. Both are files in the proprietary JKS file format. The distinction is in the use: To the best of my knowledge, Java will only use the store that is referenced by the -Djavax.net.ssl.trustStore
system property to look for certificates to trust when creating SSL connections. Same for keys and -Djavax.net.ssl.keyStore
. But in theory it's fine to use one and the same file for trust- and keystores.
If triangle.lborderA
is indeed a long then the test in the original code is trivially true, and there is no way to test it. It is also useless.
However, if triangle.lborderA
is a double, the comparison is useful and can be tested. isBiggerThanMaxLong(1e300)
does return true.
public static boolean isBiggerThanMaxLong(double in){
return in > Long.MAX_VALUE;
}
The proposed solutions are interesting and offer a good reference, however they are only partially satisfying. It is ok to manually add the separator when you have a single specific case or you know the format of the input string, but there can be cases where you want to do it programmatically on generic inputs.
With a bit of experimenting, I believe the criteria is that the path delimiter is not added if the first segment is a drive letter, meaning a single letter followed by a colon, no matter if it corresponds to a real unit.
For example:
import os
testval = ['c:','c:\\','d:','j:','jr:','data:']
for t in testval:
print ('test value: ',t,', join to "folder"',os.path.join(t,'folder'))
test value: c: , join to "folder" c:folder test value: c:\ , join to "folder" c:\folder test value: d: , join to "folder" d:folder test value: j: , join to "folder" j:folder test value: jr: , join to "folder" jr:\folder test value: data: , join to "folder" data:\folder
A convenient way to test for the criteria and apply a path correction can be to use os.path.splitdrive
comparing the first returned element to the test value, like t+os.path.sep if os.path.splitdrive(t)[0]==t else t
.
Test:
for t in testval:
corrected = t+os.path.sep if os.path.splitdrive(t)[0]==t else t
print ('original: %s\tcorrected: %s'%(t,corrected),' join corrected->',os.path.join(corrected,'folder'))
original: c: corrected: c:\ join corrected-> c:\folder original: c:\ corrected: c:\ join corrected-> c:\folder original: d: corrected: d:\ join corrected-> d:\folder original: j: corrected: j:\ join corrected-> j:\folder original: jr: corrected: jr: join corrected-> jr:\folder original: data: corrected: data: join corrected-> data:\folder
it can be probably be improved to be more robust for trailing spaces, and I have tested it only on windows, but I hope it gives an idea. See also Os.path : can you explain this behavior? for interesting details on systems other then windows.
I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:
$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war
Spring 3 supports ${my.server.port:defaultValue}
syntax.
I had this problem with my datasource in WildFly and Tomcat, connecting to a Oracle 10g.
I found that under certain conditions the statement wasn't closed even when the statement.close() was invoked. The problem was with the Oracle Driver we were using: ojdbc7.jar. This driver is intended for Oracle 12c and 11g, and it seems has some issues when is used with Oracle 10g, so I downgrade to ojdbc5.jar and now everything is running fine.
Remove all listeners in element by one js line:
element.parentNode.innerHTML += '';
Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...
# fooz.yml
foo:
bar: <%= $ENV[:some_var] %>
No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.
If you can use the template like that or the << >>
or the {{ }}
styles depending on your reader, after that you just ...
In another yml file ...
# boo.yml
development:
fooz: foo
Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.
With Eclipse and Windows:
you have to copy 2 files - xxxPROJECTxxx.properties - log4j.properties here : C:\Eclipse\CONTENER\TOMCAT\apache-tomcat-7\lib
You should have a 'skeleton' somewhere in /etc
, probably /etc/skeleton
, or check the default settings, probably /etc/default
or something. Those are scripts that define standard environment variables getting set during a login.
If it is just for your own account: check the (hidden) file ~/.profile
and ~/.login
. Or generate them, if they don't exist. These are also evaluated by the login process.
REPLACE INTO table(column_list) VALUES(value_list);
is a shorter form of
INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.
REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.
This is a work around.. not checked the speed..
INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
followed by
UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
This method allows a replace to occur without causing a trigger.
According to Lemma 22.11 of Cormen et al., Introduction to Algorithms (CLRS):
A directed graph G is acyclic if and only if a depth-first search of G yields no back edges.
This has been mentioned in several answers; here I'll also provide a code example based on chapter 22 of CLRS. The example graph is illustrated below.
CLRS' pseudo-code for depth-first search reads:
In the example in CLRS Figure 22.4, the graph consists of two DFS trees: one consisting of nodes u, v, x, and y, and the other of nodes w and z. Each tree contains one back edge: one from x to v and another from z to z (a self-loop).
The key realization is that a back edge is encountered when, in the DFS-VISIT
function, while iterating over the neighbors v
of u
, a node is encountered with the GRAY
color.
The following Python code is an adaptation of CLRS' pseudocode with an if
clause added which detects cycles:
import collections
class Graph(object):
def __init__(self, edges):
self.edges = edges
self.adj = Graph._build_adjacency_list(edges)
@staticmethod
def _build_adjacency_list(edges):
adj = collections.defaultdict(list)
for edge in edges:
adj[edge[0]].append(edge[1])
return adj
def dfs(G):
discovered = set()
finished = set()
for u in G.adj:
if u not in discovered and u not in finished:
discovered, finished = dfs_visit(G, u, discovered, finished)
def dfs_visit(G, u, discovered, finished):
discovered.add(u)
for v in G.adj[u]:
# Detect cycles
if v in discovered:
print(f"Cycle detected: found a back edge from {u} to {v}.")
# Recurse into DFS tree
if v not in finished:
dfs_visit(G, v, discovered, finished)
discovered.remove(u)
finished.add(u)
return discovered, finished
if __name__ == "__main__":
G = Graph([
('u', 'v'),
('u', 'x'),
('v', 'y'),
('w', 'y'),
('w', 'z'),
('x', 'v'),
('y', 'x'),
('z', 'z')])
dfs(G)
Note that in this example, the time
in CLRS' pseudocode is not captured because we're only interested in detecting cycles. There is also some boilerplate code for building the adjacency list representation of a graph from a list of edges.
When this script is executed, it prints the following output:
Cycle detected: found a back edge from x to v.
Cycle detected: found a back edge from z to z.
These are exactly the back edges in the example in CLRS Figure 22.4.
You need to escape the dot if you want to split on a literal dot:
String extensionRemoved = filename.split("\\.")[0];
Otherwise you are splitting on the regex .
, which means "any character".
Note the double backslash needed to create a single backslash in the regex.
You're getting an ArrayIndexOutOfBoundsException
because your input string is just a dot, ie "."
, which is an edge case that produces an empty array when split on dot; split(regex)
removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.
To avoid getting an ArrayIndexOutOfBoundsException
for this edge case, use the overloaded version of split(regex, limit)
, which has a second parameter that is the size limit for the resulting array. When limit
is negative, the behaviour of removing trailing blanks from the resulting array is disabled:
".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]
ie, when filename
is just a dot "."
, calling filename.split("\\.", -1)[0]
will return a blank, but calling filename.split("\\.")[0]
will throw an ArrayIndexOutOfBoundsException
.
I also face that problem Finally, i solved it
<meta property="og:image" itemprop="image" content="http://yourdomain.com/yourfolder/imagename.png" />
My image property
Make sure in image name there is no space, if you have two words then use underscore sign
Use CONVERT
with the Value
specifier of 101
, whilst casting your data to date
:
CONVERT(VARCHAR(10), CAST(Created_TS AS DATE), 101)
Here is the Solution i work with. Without RegEx and String.Split.
public static string TrimWhiteSpace(this string Value)
{
StringBuilder sbOut = new StringBuilder();
if (!string.IsNullOrEmpty(Value))
{
bool IsWhiteSpace = false;
for (int i = 0; i < Value.Length; i++)
{
if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
{
if (!IsWhiteSpace) //Comparison with previous Char
{
sbOut.Append(Value[i]);
IsWhiteSpace = true;
}
}
else
{
IsWhiteSpace = false;
sbOut.Append(Value[i]);
}
}
}
return sbOut.ToString();
}
so you can:
string cleanedString = dirtyString.TrimWhiteSpace();
I hope you got your answer regarding which is default constructor. But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object.
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Please refer below link for more details.
Personally, I use ... | Out-Null
because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null
and [void] ...
. $null = ...
is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null
and ... > $null
come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null
), compared to putting $null =
or [void]
before the expression to determine what happens after executing it.
Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help
command or your favorite search engine to try to find out what Out-Null
does. You get a useful result immediately, right? Now try to do the same with [void]
and $null =
. Not so easy, is it?
Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void]
, $null =
, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*
* I am presuming that Out-Null
is clear and well-known, which I don't know to be $true
. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.
First you can use a Paginator. This is as simple as:
$allUsers = User::paginate(15);
$someUsers = User::where('votes', '>', 100)->paginate(15);
The variables will contain an instance of Paginator class. all of your data will be stored under data
key.
Or you can do something like:
Old versions Laravel.
Model::all()->take(10)->get();
Newer version Laravel.
Model::all()->take(10);
For more reading consider these links:
If you want to log to the same file:
command1 >> log_file 2>&1
If you want different files:
command1 >> log_file 2>> err_file
In PHP, If your network under proxy. You should set the proxy URL and port
curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number
This is solves my problem
You can use setdefault
.
for line in list:
d.setdefault(year, []).append(value)
This works because setdefault returns the list as well as setting it on the dictionary, and because a list is mutable, appending to the version returned by setdefault is the same as appending it to the version inside the dictionary itself. If that makes any sense.
Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.
class Subscription
def warning_message
<<~HEREDOC
Subscription expiring soon!
Your free trial will expire in #{days_until_expiration} days.
Please update your billing information.
HEREDOC
end
end
Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc
The indentation of the least-indented line will be removed from each line of the content.
You can't, granted you don't have access to install plugins. But you probably have or can get Eclipse (Visual Studio can do this too).
Ctrl + N (new file) ? (choose XML file) ? (paste your XML content) ? Ctrl + Shift + K (format)
If you want to format JSON NotePad++ can do this by default with Ctrl + Alt + m
on body tag's onLoad try setting it like
document.getElementById("subEmail").style.backgroundColor = "yellow";
and after that on change of that input field check if some value is there, or paint it yellow like
function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
inputVal.style.backgroundColor = "yellow";
}
}
url
prop is deprecated as of Next.js version 6:
https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md
To get the query parameters, use getInitialProps
:
import Link from 'next/link'
const About = ({query}) => (
<div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)
About.getInitialProps = ({query}) => {
return {query}
}
export default About;
class About extends React.Component {
static getInitialProps({query}) {
return {query}
}
render() {
console.log(this.props.query) // The query is available in the props object
return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
}
}
The query object will be like: url.com?a=1&b=2&c=3
becomes: {a:1, b:2, c:3}
Correción: 3-LEN
declare @t TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',3-LEN(@t)),'') + CAST(@t AS VARCHAR)
For those that want it ISO 8601 compliant, since the other solutions do not have the T
separator nor the time offset (except Meistro's answer):
from datetime import datetime, timezone
result = datetime.fromtimestamp(1463288494, timezone.utc).isoformat('T', 'microseconds')
print(result) # 2016-05-15T05:01:34.000000+00:00
Note, I use fromtimestamp
because if I used utcfromtimestamp
I would need to chain on .astimezone(...)
anyway to get the offset.
If you don't want to go all the way to microseconds
you can choose a different unit with the
isoformat() method.
I would look at the Join operator:
from r in list join i in listofIds on r.Id equals i select r
I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.
Edit: Extension method syntax for completeness (now that I've figured it out):
var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
Update
You can now enable the Quick Boot option for Android Emulator. That will save emulator state, and it will start the emulator quickly on the next boot.
Click on Emulator edit button, then click Show Advanced Setting. Then enable Quick Boot
like below screenshot.
Android Development Tools (ADT) 9.0.0 (or later) has a feature that allows you to save state of the AVD (emulator), and you can start your emulator instantly. You have to enable this feature while creating a new AVD or you can just create it later by editing the AVD.
Also I have increased the Device RAM Size
to 1024
which results in a very fast emulator.
Refer to the given below screenshots for more information.
Creating a new AVD with the save snapshot feature.
Launching the emulator from the snapshot.
And for speeding up your emulator you can refer to Speed up your Android Emulator!:
Using ssd hard drive has too much impact and I recommend to use more suitable ram (8 or higher)
Here it is in batch file form:
@echo off
set source=%1
set dest=%2
for %%f in (%source%\*) do if not exist "%dest%\%%~nxf" copy "%%f" "%dest%\%%~nxf"
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
Let me guess
Your initial declaration of class PUBLICClass
was not public, then you made it `Public', can you try to clean and rebuild your project ?
The problem is in this line:
with pattern.findall(row) as f:
You are using the with
statement. It requires an object with __enter__
and __exit__
methods. But pattern.findall
returns a list
, with
tries to store the __exit__
method, but it can't find it, and raises an error. Just use
f = pattern.findall(row)
instead.
If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:
<div onClick=(()=>{downloadjs(url, filename)})/>
*it's jsx/react syntax, but can be used in pure html
Note: Edited to fix layout issue above
Try:
<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>
Use the "Display" style attribute with your bool model attribute to define the div's visibility.
Another alternative is that you are allowed to have multiple classes in a tag. Consider:
<div class="button big">This is a big button</div>
<div class="button small">This is a small button</div>
And the CSS:
.button {
/* all your common button styles */
}
.big {
height: 60px;
width: 100px;
}
.small {
height: 40px;
width: 70px;
}
and so on.
As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.
secondly, i think a correct constructor of the BufferedReader class will help you do your task.
String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();
this should help you.
Try this out:
grep -i 'killed process' /var/log/messages
As mentioned you might have a variable named round (of type int
) in your code and removing that should get rid of the error. For Jupyter notebooks however, simply clearing a cell or deleting it might not take the variable out of scope. In such a case, you can restart your notebook to start afresh after deleting the variable.
For length including white-space:
$("#id").val().length
For length without white-space:
$("#id").val().replace(/ /g,'').length
For removing only beginning and trailing white-space:
$.trim($("#test").val()).length
For example, the string " t e s t "
would evaluate as:
//" t e s t "
$("#id").val();
//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7
Here is a demo using all of them.
echo '<a href="' . $folder_path . '">Link text</a>';
Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.
EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?
A number of years ago (in the IE only days) I was using the <col align="right">
tag, but I just tested it and and it seems to be an IE only feature:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
</head>
<body>
<table width="100%" border="1">
<col align="left" />
<col align="left" />
<col align="right" />
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Price</th>
</tr>
<tr>
<td>3476896</td>
<td>My first HTML</td>
<td>$53</td>
</tr>
</table>
</body>
</html>
The snippet is taken from www.w3schools.com. Of course, it should not be used (unless for some reason you really target the IE rendering engine only), but I thought it would be interesting to mention it.
Edit:
Overall, I don't understand the reasoning behing abandoning this tag. It would appear to be very useful (at least for manual HTML publishing).
Try Making the Child Form's StartPosition Property set to Center Parent. This you can select from the form Properties.
f(n)
belongs to O(n)
if exists positive k
as f(n)<=k*n
f(n)
belongs to T(n)
if exists positive k1
, k2
as k1*n<=f(n)<=k2*n
A Java class that can evaluate mathematical expressions:
package test;
public class Calculator {
public static Double calculate(String expression){
if (expression == null || expression.length() == 0) {
return null;
}
return calc(expression.replace(" ", ""));
}
public static Double calc(String expression) {
if (expression.startsWith("(") && expression.endsWith(")")) {
return calc(expression.substring(1, expression.length() - 1));
}
String[] containerArr = new String[]{expression};
double leftVal = getNextOperand(containerArr);
expression = containerArr[0];
if (expression.length() == 0) {
return leftVal;
}
char operator = expression.charAt(0);
expression = expression.substring(1);
while (operator == '*' || operator == '/') {
containerArr[0] = expression;
double rightVal = getNextOperand(containerArr);
expression = containerArr[0];
if (operator == '*') {
leftVal = leftVal * rightVal;
} else {
leftVal = leftVal / rightVal;
}
if (expression.length() > 0) {
operator = expression.charAt(0);
expression = expression.substring(1);
} else {
return leftVal;
}
}
if (operator == '+') {
return leftVal + calc(expression);
} else {
return leftVal - calc(expression);
}
}
private static double getNextOperand(String[] exp){
double res;
if (exp[0].startsWith("(")) {
int open = 1;
int i = 1;
while (open != 0) {
if (exp[0].charAt(i) == '(') {
open++;
} else if (exp[0].charAt(i) == ')') {
open--;
}
i++;
}
res = calc(exp[0].substring(1, i - 1));
exp[0] = exp[0].substring(i);
} else {
int i = 1;
if (exp[0].charAt(0) == '-') {
i++;
}
while (exp[0].length() > i && isNumber((int) exp[0].charAt(i))) {
i++;
}
res = Double.parseDouble(exp[0].substring(0, i));
exp[0] = exp[0].substring(i);
}
return res;
}
private static boolean isNumber(int c) {
int zero = (int) '0';
int nine = (int) '9';
return (c >= zero && c <= nine) || c =='.';
}
public static void main(String[] args) {
System.out.println(calculate("(((( -6 )))) * 9 * -1"));
System.out.println(calc("(-5.2+-5*-5*((5/4+2)))"));
}
}
Seems to happen with some themes (cupertino/theme.css) in my case.
And the problem is the .ui-helper-hidden-accessible class which have clip property, like previous users said.
Just Overwrite it and it will be fine
$(document).ready(function() {
$("#datePicker").datepicker({ dateFormat: "yy-m-d" });
$('#ui-datepicker-div').css('clip', 'auto');
});
You could use System.Linq like this:
if (dataRows != null && dataRows.Length > 0)
{
dataTable = dataRows.AsEnumerable().CopyToDataTable();
}
One-to-Many and Many-to-One are similar in Multiplicity but not Aspect (i.e. Directionality).
The mapping of Associations between entity classes and the Relationships between tables. There are two categories of Relationships:
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
There are two ways to do what you are trying
One is a Multi-column Correlated Update
UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
FROM STAGING b
WHERE a.ID = b.ID);
You can use merge
MERGE INTO PRODUCTION a
USING ( select id, name, count
from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN
UPDATE SET a.name = b.name,
a.count = b.count
Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:
/^\d+$/.match(value)
Number(value) == value
Just select the code and
on Windows do Ctrl + Alt + L
on Linux do Ctrl + Windows Key + Alt + L
on Mac do CMD + Option + L
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
Timer.Elapsed
expects method of specific signature (with arguments object
and EventArgs
). If you want to use your PlayMusicEvent
method with additional argument evaluated during event registration, you can use lambda expression as an adapter:
myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));
Edit: you can also use shorter version:
myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);
Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.
To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.
Here is how to do it:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
This should do it.
I found it here: http://forums.asp.net/p/1331581/2678206.aspx
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server" ImageUrl="~/site/img/icons/cross.png"
CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this event?');"
AlternateText="Delete" />
</ItemTemplate>
</asp:TemplateField>
You can .write()
the content into the iframe document. Example:
<iframe id="FileFrame" src="about:blank"></iframe>
<script type="text/javascript">
var doc = document.getElementById('FileFrame').contentWindow.document;
doc.open();
doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
doc.close();
</script>
My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:
using Microsoft.VisualBasic.FileIO;
var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}
Remember to add reference to Microsoft.VisualBasic
More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html
More easy to understand (What is Lambda actually doing):
ls2=[[0,1,'f'],[4,2,'t'],[9,4,'afsd']]
def thirdItem(ls):
#return the third item of the list
return ls[2]
#Sort according to what the thirdItem function return
ls2.sort(key=thirdItem)
The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.
The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode
will give you a JSON encoded string and an idea how to properly encode yours.
jQuery('#elm-id').data('datakey')
will return an object of the string, if the string is properly encoded as json.
As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)
Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:
"{test: 1}"
(test
does not have double quotes around it)."{'test': 1}"
('test'
is using single quotes instead of double quotes)."'test'"
('test'
is using single quotes instead of double quotes).".1"
(a number must start with a digit; "0.1"
would be valid)."undefined"
(undefined
cannot be represented in a JSON string; null
, however, can be)."NaN"
(NaN
cannot be represented in a JSON string; direct representation of Infinity is also nYou should always write command after a Tab and not white space.
This applies to gcc
line (line #4) in your case. You need to insert tab before gcc
.
Also replace \rm -fr ll
with rm -fr ll
. Insert tabs before this command too.
However, I disagree the official definition of Guide to naming conventions on groupId, artifactId, and version which proposes the groupId must start with a reversed domain name you control.
com
means this project belongs to a company, and org
means this project belongs to a social organization. These are alright, but for those strange domain like xxx.tv, xxx.uk, xxx.cn, it does not make sense to name the groupId started with "tv.","cn.", the groupId should deliver the basic information of the project rather than the domain.
A Textblock itself can't do vertical alignment
The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.
<Border BorderBrush="{x:Null}" Height="50">
<TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>
Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable
Internet Explorer, Chrome, Firefox...
Cross Browser function "isVisible()"
//check if exist and is visible
function isVisible(id) {
var element = $('#' + id);
if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
return true;
} else {
return false;
}
}
Full example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
//check if exist and is visible
function isVisible(id) {
var element = $('#' + id);
if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
return true;
} else {
return false;
}
}
function check(id) {
if (isVisible(id)) {
alert('visible: true');
} else {
alert('visible: false');
}
return false;
}
</script>
<style type="text/css">
#fullname{
display: none;
}
#vote{
visibility: hidden;
}
</style>
<title>Full example: isVisible function</title>
</head>
<body>
<div id="hello-world">
Hello World!
</div>
<div id="fullname">
Fernando Mosquera Catarecha
</div>
<div id="vote">
rate it!
</div>
<a href="#" onclick="check('hello-world');">Check isVisible('hello-world')</a><br /><br />
<a href="#" onclick="check('fullname');">Check isVisible('fullname')</a><br /><br />
<a href="#" onclick="check('vote');">Check isVisible('vote')</a>
</body>
</html>
Regards,
Fernando
Running chrome.exe --start-fullscreen --app=https://google.com
will not get you Chrome in fullscreen, but in kiosk mode.
However, running chrome --start-fullscreen --app=https://google.com
(notice : it's chrome
instead of chrome.exe
) worked in my case.
Yes, absolutely, but check your syntax.
INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM courses
WHERE cid = 2
You can put a constant of the same type as gid
in its place, not just 1, of course. And, I just made up the cid
value.
You can run the pipenv
command with the --rm
option as in:
pipenv --rm
This will remove the virtualenv created for you under ~/.virtualenvs
See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm