I think this:
text.delete("1.0", tkinter.END)
Or if you did from tkinter import *
text.delete("1.0", END)
That should work
Displaying an Image
in WPF is much easier than that. Try this:
<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left"
Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom"
Grid.Row="8" Width="200" Grid.ColumnSpan="2" />
And the property can just be a string
:
public string DisplayedImage
{
get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}
Although you really should add your images to a folder named Images
in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:
public string DisplayedImage
{
get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}
UPDATE >>>
As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.
UPDATE 2 >>>
If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image
control. Using the string
property that I suggested, try this:
<StackPanel>
<Image Source="{Binding DisplayedImagePath}" />
<TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>
If you can't see the file path in the TextBlock
, then you probably haven't set your DataContext
to the instance of your view model. If you can see the text, then the problem is with your file path.
UPDATE 3 >>>
In .NET 4, the above Image.Source
values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack
path like this:
<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">
For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.
I rewrote your code in a more organized, better-practiced way:
import tkinter as tk
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Result:
Android Support V7 GridLayout library makes excess space distribution easy by accommodating the principle of weight. To make a column stretch, make sure the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity. Remember to add dependency for this library. Add com.android.support:gridlayout-v7:25.0.1 in build.gradle.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:columnCount="2"
app:rowCount="2">
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="First"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Second"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
android:text="Third"
app:layout_columnWeight="1"
app:layout_rowWeight="1" />
<TextView
android:layout_width="0dp"
android:layout_height="0dp"
android:gravity="center"
app:layout_columnWeight="1"
app:layout_rowWeight="1"
android:text="fourth"/>
</android.support.v7.widget.GridLayout>
Binding="{Binding YourColumn ,StringFormat='yyyy-MM-dd'}"
You have to create a new template for item selection like this.
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border
BorderThickness="{TemplateBinding Border.BorderThickness}"
Padding="{TemplateBinding Control.Padding}"
BorderBrush="{TemplateBinding Border.BorderBrush}"
Background="{TemplateBinding Panel.Background}"
SnapsToDevicePixels="True">
<ContentPresenter
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
You could use HorizontalContentAlignment="Stretch"
as follows:
<ListBox HorizontalContentAlignment="Stretch"/>
I met the same problem and I resolved it by setting CopyLocal
to true for the following libs:
System.Web.Http.dll
System.Web.Http.WebHost.dll
System.Net.Http.Formatting.dll
I must add that I use MVC4 and NET 4
Actually, I believe you want to use the __getattr__
special method instead.
Quote from the Python docs:
__getattr__( self, name)
Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism,__getattr__()
is not called. (This is an intentional asymmetry between__getattr__()
and__setattr__()
.) This is done both for efficiency reasons and because otherwise__setattr__()
would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the__getattribute__()
method below for a way to actually get total control in new-style classes.
Note: for this to work, the instance should not have a test
attribute, so the line self.test=20
should be removed.
I'd prefer the built in python html parser, no install no dependencies
soup = BeautifulSoup(s, "html.parser")
With a current version of the Notebook/Jupyter, you can create a Python3 kernel. After starting a new notebook application from the command line with Python 2 you should see an entry „Python 3“ in the dropdown menu „New“. This gives you a notebook that uses Python 3. So you can have two notebooks side-by-side with different Python versions.
mkdir -p ~/.ipython/kernels/python3
Create this file ~/.ipython/kernels/python3/kernel.json
with this content:
{
"display_name": "IPython (Python 3)",
"language": "python",
"argv": [
"python3",
"-c", "from IPython.kernel.zmq.kernelapp import main; main()",
"-f", "{connection_file}"
],
"codemirror_mode": {
"version": 2,
"name": "ipython"
}
}
Restart the notebook server.
Don't know how you want to format it, but you can do:
print("Created at %s:%s" % (t1.hour, t1.minute))
for example.
You can use the get(index) method to access an element from a List.
Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.
I started to write a Script to read OS and browser version that can be tested on Fiddle. Feel free to use and extend.
Breaking Change:
Since September 2020 the new Edge gets detected. So 'Microsoft Edge' is the new version based on Chromium and the old Edge is now detected as 'Microsoft Legacy Edge'!
/**
* JavaScript Client Detection
* (C) viazenetti GmbH (Christian Ludwig)
*/
(function (window) {
{
var unknown = '-';
// screen
var screenSize = '';
if (screen.width) {
width = (screen.width) ? screen.width : '';
height = (screen.height) ? screen.height : '';
screenSize += '' + width + " x " + height;
}
// browser
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browser = navigator.appName;
var version = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// Opera
if ((verOffset = nAgt.indexOf('Opera')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Opera Next
if ((verOffset = nAgt.indexOf('OPR')) != -1) {
browser = 'Opera';
version = nAgt.substring(verOffset + 4);
}
// Legacy Edge
else if ((verOffset = nAgt.indexOf('Edge')) != -1) {
browser = 'Microsoft Legacy Edge';
version = nAgt.substring(verOffset + 5);
}
// Edge (Chromium)
else if ((verOffset = nAgt.indexOf('Edg')) != -1) {
browser = 'Microsoft Edge';
version = nAgt.substring(verOffset + 4);
}
// MSIE
else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(verOffset + 5);
}
// Chrome
else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
browser = 'Chrome';
version = nAgt.substring(verOffset + 7);
}
// Safari
else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
browser = 'Safari';
version = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf('Version')) != -1) {
version = nAgt.substring(verOffset + 8);
}
}
// Firefox
else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
browser = 'Firefox';
version = nAgt.substring(verOffset + 8);
}
// MSIE 11+
else if (nAgt.indexOf('Trident/') != -1) {
browser = 'Microsoft Internet Explorer';
version = nAgt.substring(nAgt.indexOf('rv:') + 3);
}
// Other browsers
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
browser = nAgt.substring(nameOffset, verOffset);
version = nAgt.substring(verOffset + 1);
if (browser.toLowerCase() == browser.toUpperCase()) {
browser = navigator.appName;
}
}
// trim the version string
if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);
majorVersion = parseInt('' + version, 10);
if (isNaN(majorVersion)) {
version = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
// mobile version
var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);
// cookie
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
document.cookie = 'testcookie';
cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
}
// system
var os = unknown;
var clientStrings = [
{s:'Windows 10', r:/(Windows 10.0|Windows NT 10.0)/},
{s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
{s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
{s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
{s:'Windows Vista', r:/Windows NT 6.0/},
{s:'Windows Server 2003', r:/Windows NT 5.2/},
{s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
{s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
{s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
{s:'Windows 98', r:/(Windows 98|Win98)/},
{s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
{s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
{s:'Windows CE', r:/Windows CE/},
{s:'Windows 3.11', r:/Win16/},
{s:'Android', r:/Android/},
{s:'Open BSD', r:/OpenBSD/},
{s:'Sun OS', r:/SunOS/},
{s:'Chrome OS', r:/CrOS/},
{s:'Linux', r:/(Linux|X11(?!.*CrOS))/},
{s:'iOS', r:/(iPhone|iPad|iPod)/},
{s:'Mac OS X', r:/Mac OS X/},
{s:'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
{s:'QNX', r:/QNX/},
{s:'UNIX', r:/UNIX/},
{s:'BeOS', r:/BeOS/},
{s:'OS/2', r:/OS\/2/},
{s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
];
for (var id in clientStrings) {
var cs = clientStrings[id];
if (cs.r.test(nAgt)) {
os = cs.s;
break;
}
}
var osVersion = unknown;
if (/Windows/.test(os)) {
osVersion = /Windows (.*)/.exec(os)[1];
os = 'Windows';
}
switch (os) {
case 'Mac OS':
case 'Mac OS X':
case 'Android':
osVersion = /(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([\.\_\d]+)/.exec(nAgt)[1];
break;
case 'iOS':
osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
break;
}
// flash (you'll need to include swfobject)
/* script src="//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" */
var flashVersion = 'no check';
if (typeof swfobject != 'undefined') {
var fv = swfobject.getFlashPlayerVersion();
if (fv.major > 0) {
flashVersion = fv.major + '.' + fv.minor + ' r' + fv.release;
}
else {
flashVersion = unknown;
}
}
}
window.jscd = {
screen: screenSize,
browser: browser,
browserVersion: version,
browserMajorVersion: majorVersion,
mobile: mobile,
os: os,
osVersion: osVersion,
cookies: cookieEnabled,
flashVersion: flashVersion
};
}(this));
alert(
'OS: ' + jscd.os +' '+ jscd.osVersion + '\n' +
'Browser: ' + jscd.browser +' '+ jscd.browserMajorVersion +
' (' + jscd.browserVersion + ')\n' +
'Mobile: ' + jscd.mobile + '\n' +
'Flash: ' + jscd.flashVersion + '\n' +
'Cookies: ' + jscd.cookies + '\n' +
'Screen Size: ' + jscd.screen + '\n\n' +
'Full User Agent: ' + navigator.userAgent
);
Check out the split function of String Here, and use it something like this String[] results = input.split("\\s+");
. The regular expresion bit spilts on whitespaces, it should do the trick
enum ServicePlatform {
UPLAY = "uplay",
PSN = "psn",
XBL = "xbl"
}
becomes:
{ UPLAY: 'uplay', PSN: 'psn', XBL: 'xbl' }
so
ServicePlatform.UPLAY in ServicePlatform // false
SOLUTION:
ServicePlatform.UPLAY.toUpperCase() in ServicePlatform // true
I had the same issue caused by two things:
So after I uninstalled the 32 bit Java 1.7, installed the correct one and added the javaw.exe path, eclipse fired up with no more errors
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat
takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date
. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Date
provides a getTime()
method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat
a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)#divID {
background-image: url("http://imageurlhere.com");
background-repeat: no-repeat;
width: auto; /*or your image's width*/
height: auto; /*or your image's height*/
margin: 0;
padding: 0;
}
OTRS, Cerberus
For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170
static void Main()
{
string input = "OneTwoThree";
//Get last 5 characters
string sub = input.Substring(6);
Console.WriteLine("Substring: {0}", sub); // Output Three.
}
Substring(0, 3)
- Returns substring of first 3 chars. //One
Substring(3, 3)
- Returns substring of second 3 chars. //Two
Substring(6)
- Returns substring of all chars after first 6. //Three
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
Run these commands in the terminal:
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
Run these commands separately as each command requires confirmation & if run as a block, the command below the one currently running will cancel the confirmation (leading to the command not being run).
Please refer to How do I uninstall Mysql?
Assign the placeholder to a class selector like this:
.form-control::-webkit-input-placeholder { color: white; } /* WebKit, Blink, Edge */
.form-control:-moz-placeholder { color: white; } /* Mozilla Firefox 4 to 18 */
.form-control::-moz-placeholder { color: white; } /* Mozilla Firefox 19+ */
.form-control:-ms-input-placeholder { color: white; } /* Internet Explorer 10-11 */
.form-control::-ms-input-placeholder { color: white; } /* Microsoft Edge */
It will work then since a stronger selector was probably overriding your global. I'm on a tablet so i cant inspect and confirm which stronger selector it was :) But it does work I tried it in your fiddle.
This also answers your second question. By assigning it to a class or id and giving an input only that class you can control what inputs to style.
After all the Jquery script tag's add
<script>jQuery.noConflict();</script>
to avoid the conflict between Prototype and Jquery.
In order to get local time in pure Javascript use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
Sometimes you do start the debug mode but the debugger doesn't actually get attached/gets detached. I've also had this issue a few times when my laptop was reacting really slowly. A reboot always solved it for me.
Also try doing a clean all (works miracles in Eclipse).
I arrived at this page looking to turn off scale mode for good, so I figured I would share what I found:
VBoxManage setextradata global GUI/Input/MachineShortcuts "ScaleMode=None"
Running this in my host's terminal worked like a charm for me.
Source: https://forums.virtualbox.org/viewtopic.php?f=8&t=47821
For me on Raspbian it works only this way (old password added):
#!/usr/bin/env bash
username="pi"
password="Szevasz123"
new_ps="Szevasz1234"
passwd ${username} << EOD
${password}
${new_ps}
${new_ps}
EOD
You've got the right idea, so here's how to go ahead: the onclick
handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php
in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
Another GCD alternative is a barrier:
dispatch_queue_t queue = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"start one!\n");
sleep(4);
NSLog(@"end one!\n");
});
dispatch_async(queue, ^{
NSLog(@"start two!\n");
sleep(2);
NSLog(@"end two!\n");
});
dispatch_barrier_async(queue, ^{
NSLog(@"Hi, I'm the final block!\n");
});
Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.
I slightly modified your stored procedure (to use SCOPE_IDENTITY
) and it looks like this:
CREATE PROCEDURE usp_InsertContract
@ContractNumber varchar(7),
@NewId int OUTPUT
AS
BEGIN
INSERT INTO [dbo].[Contracts] (ContractNumber)
VALUES (@ContractNumber)
SELECT @NewId = SCOPE_IDENTITY()
END
I tried this and it works just fine (with that modified stored procedure):
// define connection and command, in using blocks to ensure disposal
using(SqlConnection conn = new SqlConnection(pvConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.usp_InsertContract", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@ContractNumber", SqlDbType.VarChar, 7);
cmd.Parameters.Add("@NewId", SqlDbType.Int).Direction = ParameterDirection.Output;
// set parameter values
cmd.Parameters["@ContractNumber"].Value = contractNumber;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @NewId
int contractID = Convert.ToInt32(cmd.Parameters["@NewId"].Value);
conn.Close();
}
Does this work in your environment, too? I can't say why your original code won't work - but when I do this here, VS2010 and SQL Server 2008 R2, it just works flawlessly....
If you don't get back a value - then I suspect your table Contracts
might not really have a column with the IDENTITY
property on it.
In C shell - The ampersand is after the greater-than symbol
make >& filename
Here is what i found googling around:
var fileupload = require("express-fileupload");
app.use(fileupload());
Which is pretty simple mechanism for uploads
app.post("/upload", function(req, res)
{
var file;
if(!req.files)
{
res.send("File was not found");
return;
}
file = req.files.FormFieldName; // here is the field name of the form
res.send("File Uploaded");
});
The answer that works on Ubuntu18, python3, opencv 3.2.0 is similar to the one above. But with the change in line cv2.waitKey(0)
. that means the program waits until a button is pressed.
With this code I found the key value for the arrow buttons: arrow up (82), down (84), arrow left(81) and Enter(10) and etc..
import cv2
img = cv2.imread('sof.jpg') # load a dummy image
while(1):
cv2.imshow('img',img)
k = cv2.waitKey(0)
if k==27: # Esc key to stop
break
elif k==-1: # normally -1 returned,so don't print it
continue
else:
print k # else print its value
You can also use firstOrCreate
OR firstOrNew
// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]);
// update record
$post->title = "Updated title";
$post->save();
Hope it will help you :)
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
You have to just add the index_col=False
parameter
df1 = pd.read_csv('foo.csv',
header=0,
index_col=False,
names=["dummy", "date", "loc", "x"],
usecols=["dummy", "date", "loc", "x"],
parse_dates=["date"])
print df1
No, but you should be careful when using IF...ELSE...END IF in stored procs. If your code blocks are radically different, you may suffer from poor performance because the procedure plan will need to be re-cached each time. If it's a high-performance system, you may want to compile separate stored procs for each code block, and have your application decide which proc to call at the appropriate time.
You can use the file_get_contents
function to access remote files. See http://php.net/manual/en/function.file-get-contents.php for details.
The problem seems to be that block
elements only scale up to 100% of their containing element, no matter how big their content is—it just overflows. However, making them inline-block
elements apparently resizes their width to their actual content.
HTML:
<div id="container">
<div class="wide">
foooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
</div>
<div class="wide">
bar
</div>
</div>
CSS:
.wide { min-width: 100%; display: inline-block; background-color: yellow; }
#container { display: inline-block; }
(The container
element addresses your follow-up question to make the second div
as big as the previous one, and not just the screen width.)
I also set up a JS fiddle showing my demo code.
If you run into any troubles (esp. cross-browser issues) with inline-block
, looking at Block-level elements within display: inline-block might help.
When storing images in SQL Server do not use the 'image' datatype, according to MS it is being phased out in new versions of SQL server. Use varbinary(max) instead
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];
If anybody needs to retrive specific RowDataPacket object from multiple queries, here it is.
Before you start
Important: Ensure you enable multipleStatements
in your mysql connection like so:
// Connection to MySQL
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'TEST',
multipleStatements: true
});
Multiple Queries
Let's say we have multiple queries running:
// All Queries are here
const lastCheckedQuery = `
-- Query 1
SELECT * FROM table1
;
-- Query 2
SELECT * FROM table2;
`
;
// Run the query
db.query(lastCheckedQuery, (error, result) => {
if(error) {
// Show error
return res.status(500).send("Unexpected database error");
}
If we console.log(result)
you'll get such output:
[
[
RowDataPacket {
id: 1,
ColumnFromTable1: 'a',
}
],
[
RowDataPacket {
id: 1,
ColumnFromTable2: 'b',
}
]
]
Both results show for both tables.
Here is where basic Javascript array's come in place https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
To get data from table1
and column named ColumnFromTable1
we do
result[0][0].ColumnFromTable1 // Notice the double [0]
which gives us result of a
.
Yes ! .java file can contain only one public class.
If you want these two classes to be public they have to be put into two .java files: A.java and B.java.
Easy to map different set of list by linq without for loop
var List1= new List<Entities1>();
var List2= new List<Entities2>();
var List2 = List1.Select(p => new Entities2
{
EntityCode = p.EntityCode,
EntityId = p.EntityId,
EntityName = p.EntityName
}).ToList();
Here is a much cleaner syntax if using rails 4+
<%= f.text_field :attr, placeholder: "placeholder text" %>
So rails 4+
can now use this syntax instead of the hash syntax
I found the solution in this topic and I code this:
$cards = DB::select("SELECT
cards.id_card,
cards.hash_card,
cards.`table`,
users.name,
0 as total,
cards.card_status,
cards.created_at as last_update
FROM cards
LEFT JOIN users
ON users.id_user = cards.id_user
WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
UNION
SELECT
cards.id_card,
orders.hash_card,
cards.`table`,
users.name,
sum(orders.quantity*orders.product_price) as total,
cards.card_status,
max(orders.created_at) last_update
FROM menu.orders
LEFT JOIN cards
ON cards.hash_card = orders.hash_card
LEFT JOIN users
ON users.id_user = cards.id_user
GROUP BY hash_card
ORDER BY id_card ASC");
If you want to test private methods, have a look at PrivateObject
and PrivateType
in the Microsoft.VisualStudio.TestTools.UnitTesting
namespace. They offer easy to use wrappers around the necessary reflection code.
Docs: PrivateType, PrivateObject
For VS2017 & 2019, you can find these by downloading the MSTest.TestFramework nuget
There is HTML entity ✓ but it doesn't work in some older browsers.
As always, I recommend reading this article about date and time in Java so that you understand it.
The basic idea is that 'under the hood' everything is done in UTC milliseconds since the epoch. This means it is easiest if you operate without using time zones at all, with the exception of String formatting for the user.
Therefore I would skip most of the steps you have suggested.
Alternatively, you can use Joda time. I have heard it is a much more intuitive datetime API.
It depends what you are looking for, if you are just looking to see if it is empty just use empty
as it checks whether it is set as well, if you want to know whether something is set or not use isset
.
Empty
checks if the variable is set and if it is it checks it for null, "", 0, etc
Isset
just checks if is it set, it could be anything not null
With empty
, the following things are considered empty:
From http://php.net/manual/en/function.empty.php
As mentioned in the comments the lack of warning is also important with empty()
PHP Manual says
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
Regarding isset
PHP Manual says
isset() will return FALSE if testing a variable that has been set to NULL
Your code would be fine as:
<?php
$var = '23';
if (!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
For example:
$var = "";
if(empty($var)) // true because "" is considered empty
{...}
if(isset($var)) //true because var is set
{...}
if(empty($otherVar)) //true because $otherVar is null
{...}
if(isset($otherVar)) //false because $otherVar is not set
{...}
I found a solution for my problem while writing my question !
Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)
I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)
So it seems the problem comes from the use of RDP (windows7 and 8)
Update 2017: Problem occurs on Windows 10 aswell.
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
You can convert a java 8 stream to an array using this simple code block:
String[] myNewArray3 = myNewStream.toArray(String[]::new);
But let's explain things more, first, let's Create a list of string filled with three values:
String[] stringList = {"Bachiri","Taoufiq","Abderrahman"};
Create a stream from the given Array :
Stream<String> stringStream = Arrays.stream(stringList);
we can now perform some operations on this stream Ex:
Stream<String> myNewStream = stringStream.map(s -> s.toUpperCase());
and finally convert it to a java 8 Array using these methods:
1-Classic method (Functional interface)
IntFunction<String[]> intFunction = new IntFunction<String[]>() {
@Override
public String[] apply(int value) {
return new String[value];
}
};
String[] myNewArray = myNewStream.toArray(intFunction);
2 -Lambda expression
String[] myNewArray2 = myNewStream.toArray(value -> new String[value]);
3- Method reference
String[] myNewArray3 = myNewStream.toArray(String[]::new);
Method reference Explanation:
It's another way of writing a lambda expression that it's strictly equivalent to the other.
Try just importing the functions needed from main.py? So,
from main import SomeFunction
It could be that you've named a function in batch.py the same as one in main.py, and when you import main.py the program runs the main.py function instead of the batch.py function; doing the above should fix that. I hope.
See How to Make Dialogs.
You can use:
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
And you can also change the symbol to an error message or an warning. E.g see JOptionPane Features.
Since Spring 5 you just need to implement the interface WebMvcConfigurer
:
public class MvcConfig implements WebMvcConfigurer {
This is because Java 8 introduced default methods on interfaces which cover the functionality of the WebMvcConfigurerAdapter
class
See here:
Read file contents into a variable:
for /f "delims=" %%x in (version.txt) do set Build=%%x
or
set /p Build=<version.txt
Both will act the same with only a single line in the file, for more lines the for
variant will put the last line into the variable, while set /p
will use the first.
Using the variable – just like any other environment variable – it is one, after all:
%Build%
So to check for existence:
if exist \\fileserver\myapp\releasedocs\%Build%.doc ...
Although it may well be that no UNC paths are allowed there. Can't test this right now but keep this in mind.
I am using following command to get latest images
sudo docker-compose down -rmi all
sudo docker-compose up -d
For recent SQL:
select * from v$sql
For history:
select * from dba_hist_sqltext
Use copyOfRange method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
For more details:
Since anonymous classes extend the given class you can store them in a variable.
eg.
Thread t = new Thread()
{
public void run() {
System.out.println("blah");
}
};
t.start();
Alternatively, you can just call the start method on the object you have immediately created.
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
// similar to new Thread().start();
Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).
eg
new Thread(new Runnable()
{
@Override
public void run() {
System.out.println("blah");
}
}).start();
You can select the columns of a groupby:
In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
Y1961 Y1962 Y1963
Country Item_Code
Afghanistan 15 10 20 30
25 10 20 30
Angola 15 30 40 50
25 30 40 50
Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.
You can simply use setInterval
to create such timer in Angular, Use this Code for timer -
timeLeft: number = 60;
interval;
startTimer() {
this.interval = setInterval(() => {
if(this.timeLeft > 0) {
this.timeLeft--;
} else {
this.timeLeft = 60;
}
},1000)
}
pauseTimer() {
clearInterval(this.interval);
}
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p>{{timeLeft}} Seconds Left....</p>
import { timer } from 'rxjs';
observableTimer() {
const source = timer(1000, 2000);
const abc = source.subscribe(val => {
console.log(val, '-');
this.subscribeTimer = this.timeLeft - val;
});
}
<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}
For more information read here
You can use DataFrame.select_dtypes
to select string
columns and then apply
function str.strip
.
Notice: Values cannot be types
like dicts
or lists
, because their dtypes
is object
.
df_obj = df.select_dtypes(['object'])
print (df_obj)
0 a
1 c
df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)
0 1
0 a 10
1 c 5
But if there are only a few columns use str.strip
:
df[0] = df[0].str.strip()
Microsoft Support says "Maximum URL length is 2,083 characters in Internet Explorer".
IE has problems with URLs longer than that. Firefox seems to work fine with >4k chars.
Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:
resources :articles do
resources :comments
end
You get paths like:
/articles/42
/articles/42/comments/99
routed to controllers at
app/controllers/articles_controller.rb
app/controllers/comments_controller.rb
just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.
But partials and forms become tricky. Note the square brackets:
<%= form_for [@article, @comment] do |f| %>
Most important, if you want a URI, you may need something like this:
article_comment_path(@article, @comment)
Alternatively:
[@article, @comment]
as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects
For example, inside a collections partial with comment_item
supplied for iteration,
<%= link_to "delete", article_comment_path(@article, comment_item),
:method => :delete, :confirm => "Really?" %>
What jamuraa says may work in the context of Article, but it did not work for me in various other ways.
There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources
Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:
# POST /comments
post :create, :comment => {:article_id=>42, ...}
In order to test the route that they may prefer, they need to do it this way:
# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}
I learned this because my unit-tests started failing when I switched from this:
resources :comments
resources :articles do
resources :comments
end
to this:
resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:
resources :comments
resources :articles do
resources :comments, :only => [:create, :index, :new]
end
Sorry for the long answer. Not many people are aware of the subtleties, I think.
You can try to do my answer,
you wrote this:
<?php
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
?>
And in your case I would do this:
<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
$items[] = $username;
} ?>
As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)
<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
$items[] = $username;
}
?>
while
is faster, but the last example is only a result of an observation. :)
The biggest problem I ran into doing this was cases like "Bob R. Smith, Jr.". The algorithm I used is posted at http://www.blackbeltcoder.com/Articles/strings/splitting-a-name-into-first-and-last-names. My code is in C# but you could port it if you must have in SQL.
The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.
The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.
you can try the following code
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
if (dt.Columns.Count == 0)
{
dt.Columns.Add("PayScale", typeof(string));
dt.Columns.Add("IncrementAmt", typeof(string));
dt.Columns.Add("Period", typeof(string));
}
DataRow NewRow = dt.NewRow();
NewRow[0] = TextBox1.Text;
NewRow[1] = TextBox2.Text;
dt.Rows.Add(NewRow);
GridView1.DataSource = dt;
GridViewl.DataBind();
}
here payscale,incrementamt and period are database field name.
You can use one of the following options:
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >
<link href="{{ URL::asset('css/app.css') }}" rel="stylesheet" type="text/css" >
{!! Html::style( asset('css/app.css')) !!}
An extension method for this which makes use of SemaphoreSlim and also allows to set maximum degree of parallelism
/// <summary>
/// Concurrently Executes async actions for each item of <see cref="IEnumerable<typeparamref name="T"/>
/// </summary>
/// <typeparam name="T">Type of IEnumerable</typeparam>
/// <param name="enumerable">instance of <see cref="IEnumerable<typeparamref name="T"/>"/></param>
/// <param name="action">an async <see cref="Action" /> to execute</param>
/// <param name="maxDegreeOfParallelism">Optional, An integer that represents the maximum degree of parallelism,
/// Must be grater than 0</param>
/// <returns>A Task representing an async operation</returns>
/// <exception cref="ArgumentOutOfRangeException">If the maxActionsToRunInParallel is less than 1</exception>
public static async Task ForEachAsyncConcurrent<T>(
this IEnumerable<T> enumerable,
Func<T, Task> action,
int? maxDegreeOfParallelism = null)
{
if (maxDegreeOfParallelism.HasValue)
{
using (var semaphoreSlim = new SemaphoreSlim(
maxDegreeOfParallelism.Value, maxDegreeOfParallelism.Value))
{
var tasksWithThrottler = new List<Task>();
foreach (var item in enumerable)
{
// Increment the number of currently running tasks and wait if they are more than limit.
await semaphoreSlim.WaitAsync();
tasksWithThrottler.Add(Task.Run(async () =>
{
await action(item).ContinueWith(res =>
{
// action is completed, so decrement the number of currently running tasks
semaphoreSlim.Release();
});
}));
}
// Wait for all tasks to complete.
await Task.WhenAll(tasksWithThrottler.ToArray());
}
}
else
{
await Task.WhenAll(enumerable.Select(item => action(item)));
}
}
Sample Usage:
await enumerable.ForEachAsyncConcurrent(
async item =>
{
await SomeAsyncMethod(item);
},
5);
Works fine for me
See example here. http://jsfiddle.net/blowsie/c6VAy/
Make sure your jquery is inside $(document).ready
function or similar.
Also you can improve your code by using jquery data
$('#amount').data('min','1000');
<div id="amount" data-min=""></div>
Update,
A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/
Sometimes even the simplest things can make a difference. One of these simple items that should be part of every stored procedure is SET NOCOUNT ON
. This one line of code, put at the top of a stored procedure turns off the messages that SQL Server sends back to the client after each T-SQL statement is executed. This is performed for all SELECT
, INSERT
, UPDATE
, and DELETE
statements. Having this information is handy when you run a T-SQL statement in a query window, but when stored procedures are run there is no need for this information to be passed back to the client.
By removing this extra overhead from the network it can greatly improve overall performance for your database and application.
If you still need to get the number of rows affected by the T-SQL statement that is executing you can still use the @@ROWCOUNT
option. By issuing a SET NOCOUNT ON
this function (@@ROWCOUNT
) still works and can still be used in your stored procedures to identify how many rows were affected by the statement.
If your compiler supports C++11 standard, there is a constructor inheritance using using
(pun intended). For more see Wikipedia C++11 article. You write:
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
using A::A;
};
This is all or nothing - you cannot inherit only some constructors, if you write this, you inherit all of them. To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them.
Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
From matplotlib version 2.1 onwards, you may use a figure legend. Instead of ax.legend()
, which produces a legend with the handles from the axes ax
, one can create a figure legend
fig.legend(loc="upper right")
which will gather all handles from all subplots in the figure. Since it is a figure legend, it will be placed at the corner of the figure, and the loc
argument is relative to the figure.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0,10)
y = np.linspace(0,10)
z = np.sin(x/3)**2*98
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x,y, '-', label = 'Quantity 1')
ax2 = ax.twinx()
ax2.plot(x,z, '-r', label = 'Quantity 2')
fig.legend(loc="upper right")
ax.set_xlabel("x [units]")
ax.set_ylabel(r"Quantity 1")
ax2.set_ylabel(r"Quantity 2")
plt.show()
In order to place the legend back into the axes, one would supply a bbox_to_anchor
and a bbox_transform
. The latter would be the axes transform of the axes the legend should reside in. The former may be the coordinates of the edge defined by loc
given in axes coordinates.
fig.legend(loc="upper right", bbox_to_anchor=(1,1), bbox_transform=ax.transAxes)
setText
is changing the text content to exactly what you give it, not appending it.
Convert the String
from the field first, then apply it directly...
String value = "This Is A Test";
StringBuilder sb = new StringBuilder(value);
for (int index = 0; index < sb.length(); index++) {
char c = sb.charAt(index);
if (Character.isLowerCase(c)) {
sb.setCharAt(index, Character.toUpperCase(c));
} else {
sb.setCharAt(index, Character.toLowerCase(c));
}
}
SecondTextField.setText(sb.toString());
[Original answer]: You can still use launchctl setenv variablename value
to set a variable so that is picked up by all applications (graphical applications started via the Dock or Spotlight, in addition to those started via the terminal).
Obviously you will not want to do this every time you login.
[Edit]: To avoid this, launch AppleScript Editor
, enter a command like this:
do shell script "launchctl setenv variablename value"
(Use multiple lines if you want to set multiple variables)
Now save (?
+s
) as File format: Application. Finally open System Settings
? Users & Groups ? Login Items and add your new application.
[Original answer]: To work around this place all the variables you wish to define in a short shell script, then have a look at this previous answer about how to run a script on MacOS login. That way the the script will be invoked when the user logs in.
[Edit]: Neither solution is perfect as the variables will only be set for that specific user but I am hoping/guessing that may be all you require.
If you do have multiple users you could either manually set a Login Item for each of them or place a copy of com.user.loginscript.plist in each of their local Library/LaunchAgents directories, pointing at the same shell script.
Granted, neither of these workarounds is as convenient as /etc/launchd.conf.
[Further Edit]: A user below mentions that this did not work for him. However I have tested on multiple Yosemite machines and it does work for me. If you are having a problem, remember that you will need to restart applications for this to take effect. Additionally if you set variables in the terminal via ~/.profile or ~/.bash_profile, they will override things set via launchctl setenv for applications started from the shell.
You can try:
WebElement getmenu= driver.findElement(By.xpath("//*[@id='ui-id-2']/span[2]")); //xpath the parent
Actions act = new Actions(driver);
act.moveToElement(getmenu).perform();
Thread.sleep(3000);
WebElement clickElement= driver.findElement(By.linkText("Sofa L"));//xpath the child
act.moveToElement(clickElement).click().perform();
If you had case the web have many category, use the first method. For menu you wanted, you just need the second method.
I tried using the iframe embed code and the HTML5 player appeared, however, for some reason the iframe was completely breaking my site.
I messed around with the old object embed code and it works perfectly fine. So if you're having problems with the iframe here's the code i used:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3"/>
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
hope this is useful for someone
I used git svn
, and had this problem for one file. Using ls-tree
for each ancestor of the file, I noticed that one had 2 subfolders - Submit
and submit
. Since I was on Windows, they couldn't both be checked out, causing this issue.
The solution was to delete one of them directly from TortoiseSVN
Repo-browser
, then to run git svn fetch
followed by git reset --hard origin/trunk
.
You will find below some code for reading unencrypted RSA keys encoded in the following formats:
-----BEGIN RSA PRIVATE KEY-----
)-----BEGIN PRIVATE KEY-----
) It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream
or DerValue
).
private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";
public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);
if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
// OpenSSL / PKCS#1 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
}
if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
// PKCS#8 Base64 PEM encoded file
keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
}
// We assume it's a PKCS#8 DER encoded binary file
return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}
private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
try {
return keyFactory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
throw new IllegalArgumentException("Unexpected key format!", e);
}
}
private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
// We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
int pkcs1Length = pkcs1Bytes.length;
int totalLength = pkcs1Length + 22;
byte[] pkcs8Header = new byte[] {
0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
0x2, 0x1, 0x0, // Integer (0)
0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
};
byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
return readPkcs8PrivateKey(pkcs8bytes);
}
private static byte[] join(byte[] byteArray1, byte[] byteArray2){
byte[] bytes = new byte[byteArray1.length + byteArray2.length];
System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
return bytes;
}
EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(''ER0002'')'
; worked for me.
closing the varchar
/string
with two pairs of single quotes did the trick. Other option could be to use using
keyword, EXECUTE IMMEDIATE 'insert into MY_TBL (Col) values(:text_string)' using 'ER0002'
; Remember using
keyword will not work, if you are using EXECUTE IMMEDIATE
to execute DDL's with parameters, however, using quotes will work for DDL's.
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
Note: You can do it for as many earlier versions you want, i.e. IE9, IE8 and so on.
lines = bigstring.split('\n')
lines = [line for line in lines if line.strip()]
If you are trying to test your app coded in android studio through your android phone, its generally the issue of your phone. Just uncheck all the USB debugging options and toggle the developer options to OFF. Then restart your phone and switch the developer and USB debugging on. You are ready to go!
If you knew the Class
of ImplementationType
you could create an instance of it. So what you are trying to do is not possible.
Via PowerShell anonymously:
(Invoke-WebRequest https://login.windows.net/YOURDIRECTORYNAME.onmicrosoft.com/.well-known/openid-configuration|ConvertFrom-Json).token_endpoint.Split('/')[3]
I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.
You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.
Here's some client side C# code to get a token:
//using System;
//using System.Collections.Generic;
//using System.Net;
//using System.Net.Http;
//string token = GetToken("https://localhost:<port>/", userName, password);
static string GetToken(string url, string userName, string password) {
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password" ),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "Password", password )
};
var content = new FormUrlEncodedContent(pairs);
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient()) {
var response = client.PostAsync(url + "Token", content).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
In order to use the token add it to the header of the request:
//using System;
//using System.Collections.Generic;
//using System.Net;
//using System.Net.Http;
//var result = CallApi("https://localhost:<port>/something", token);
static string CallApi(string url, string token) {
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
using (var client = new HttpClient()) {
if (!string.IsNullOrWhiteSpace(token)) {
var t = JsonConvert.DeserializeObject<Token>(token);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
}
var response = client.GetAsync(url).Result;
return response.Content.ReadAsStringAsync().Result;
}
}
Where Token is:
//using Newtonsoft.Json;
class Token
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string userName { get; set; }
[JsonProperty(".issued")]
public string issued { get; set; }
[JsonProperty(".expires")]
public string expires { get; set; }
}
Now for the server side:
In Startup.Auth.cs
var oAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider("self"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// https
AllowInsecureHttp = false
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(oAuthOptions);
And in ApplicationOAuthProvider.cs the code that actually grants or denies access:
//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
throw new ArgumentNullException("publicClientId");
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
var properties = new AuthenticationProperties(propertyDictionary);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
// Token is validated.
context.Validated(ticket);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
context.Validated();
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
var expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
context.Validated();
}
return Task.FromResult<object>(null);
}
}
As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.
Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.
You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.
Although, I'm a big fan of Kanban Tool service (it has everything you need except free of charge) and therefore it's difficult for me to stay objective, I think that should go for Trello or Kanban Flow. Both are free and both provide basic features that are essential for agile process managers and their teams.
Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen.
It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name.
Activate a conda environment in your terminal using source activate <environment name>
before you run jupyter notebook
. This sets the default environment for Jupyter Notebooks. Otherwise, the [Root] environment is the default.
You can also create new environments from within Jupyter Notebook (home screen, Conda tab, and then click the plus sign).
And you can create a notebook in any environment you want. Select the "Files" tab on the home screen and click the "New" dropdown menu, and in that menu select a Python environment from the list.
Try this link.... horizontal rule
That should do the trick.
The code below is xml.
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:background="#FF00FF00" />
You can use the google docs OCR reader.
Right now it will only work in some browsers, and as far as I can see you haven't actually linked to a file, so that would explain why it is not playing.
but as you want a live stream (which I have not tested with)
check out Streaming via RTSP or RTP in HTML5
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
import csv
toCSV = [{'name':'bob','age':25,'weight':200},
{'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(toCSV)
EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.
I think that Joseph flipped controller and action. First comes the action then the controller. This is somewhat strange, but the way the signature looks.
Just to clarify things, this is the version that works (adaption of Joseph's example):
Html.ActionLink(article.Title,
"Login", // <-- ActionMethod
"Item", // <-- Controller Name
new { id = article.ArticleID }, // <-- Route arguments.
null // <-- htmlArguments .. which are none
)
PHP Implementation:
function encode($message)
{
$length = strlen($message);
$bytesHeader = [];
$bytesHeader[0] = 129; // 0x1 text frame (FIN + opcode)
if ($length <= 125) {
$bytesHeader[1] = $length;
} else if ($length >= 126 && $length <= 65535) {
$bytesHeader[1] = 126;
$bytesHeader[2] = ( $length >> 8 ) & 255;
$bytesHeader[3] = ( $length ) & 255;
} else {
$bytesHeader[1] = 127;
$bytesHeader[2] = ( $length >> 56 ) & 255;
$bytesHeader[3] = ( $length >> 48 ) & 255;
$bytesHeader[4] = ( $length >> 40 ) & 255;
$bytesHeader[5] = ( $length >> 32 ) & 255;
$bytesHeader[6] = ( $length >> 24 ) & 255;
$bytesHeader[7] = ( $length >> 16 ) & 255;
$bytesHeader[8] = ( $length >> 8 ) & 255;
$bytesHeader[9] = ( $length ) & 255;
}
$str = implode(array_map("chr", $bytesHeader)) . $message;
return $str;
}
When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:
as.numeric(df[1,])
As @Roland suggests, unlist(df[1,])
will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,]))
is another, slightly more explicit way to get to the same result.
As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,])
instead.
After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.
Once you are connected to the local instance, right click on Databases and create a new database.
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request.
I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead.
It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs.
When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up):
[Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success
The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.
Mozilla's MDN suggests something like the following [source]:
p {
width: intrinsic; /* Safari/WebKit uses a non-standard name */
width: -moz-max-content; /* Firefox/Gecko */
width: -webkit-max-content; /* Chrome */
}
Even if this question has resolved, I want to add my advice about that.... since as developer I ignored.
Is important to know that we're talking about MSSQL xp_cmdshell enabled is critical to security, as indicated in the message warning:
Blockquote SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. [...]
Leaving the service enabled is a kind of weakness, that for example in a web-app could reflect and execute commands SQL from an attacker.
The popular CWE-89: SQL Injection
it could be weakness in the our software, and therefore these type of scenarios could pave the way to possible attacks, such as CAPEC-108: Command Line Execution through SQL Injection
I hope to have done something pleasant, we Developers and Engineer do things with awareness and we will be safer!
try this:
type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
var headers = XMLHttpRequest.getAllResponseHeaders();
}
In the root directory of the project there is a hidden .git
directory that contains configuration, the repository etc.
Yes, you need to close Connection
. Otherwise, the database client will typically keep the socket connection and other resources open.
I just did 'svn revert /blabla' and it worked, the folder is back and I can svn delete it
Give boon a try:
https://github.com/RichardHightower/boon
It is wicked fast:
https://github.com/RichardHightower/json-parsers-benchmark
Don't take my word for it... check out the gatling benchmark.
https://github.com/gatling/json-parsers-benchmark
(Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)
It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.
It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).
It also has the fastest JSON to JavaBean mode too.
It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.
Following the @greg0ire suggestion in comments:
<input type="submit" name="add_tag" value="Lägg till tag" />
In your server side, you'll do something like:
if (request.getParameter("add_tag") != null)
tags.addTag( /*...*/ );
(Since I don't know that language (java?), there may be syntax errors.)
I would prefer the <button>
solution, but it doesn't work as expected on IE < 9.
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
There's no difference at all, VanillaJS
is just a way to refer to native (non-extended and standards-based) JavaScript. Generally speaking it's a term of contrast when using libraries and frameworks like jQuery and React. Website www.vanilla-js.com lays emphasis on it as a joke, by talking 'bout VanillaJS
as though it were a fast, lightweight, and cross-platform framework. That muddies the waters! Thus, it can be a little philosophical question: "how many things do I compile to Vanilla JavaScript
without being VanillaJS
themselves?" So, a mere guideline for that is: if you can write the code and run it in any current web-browser without additional tools or so called compile steps, it might be VanillaJS
.
Running macOS Cataline 10.15, the keychain caching method was not working for me. And I wanted to use https://
not ssh
Here is what worked for me:
git remote rm origin
git remote add origin https://your_git_username:[email protected]/path_to_your_git.git
This should work on GitLab too
Make sure if the username contains an email address, to remove the @email
part or you'll get an error stating URL using bad/illegal format or missing URL
.
Hope this helps!
From IEEE floating-point exceptions in C++ :
This page will answer the following questions.
- My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
- How can I tell if a number is really a number and not a NaN or an infinity?
- How can I find out more details at runtime about kinds of NaNs and infinities?
- Do you have any sample code to show how this works?
- Where can I learn more?
These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.
Debugging 1.#IND, 1.#INF, nan, and inf
If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.
Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.
In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.
You can try to start Eclipse
first with the -clean
option.
On Windows you can add the -clean
option to your shortcut for eclipse. On Linux
you can simply add it when starting Eclipse
from the command line.
list1=['x','y','z','a','b','c','d','e','f','g']
find=raw_input("Enter string to be found")
l=list1.index(find)
list1a=[:l]
list1b=[l:]
if you cannot access data folder on Android Device Monitor
cmd
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools
(Where you located sdk folder)
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb shell
generic_x86:/ $
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb kill-server
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb start-server
* daemon not running. starting it now at tcp:5037 *
* daemon started successfully *
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>adb root
C:\Users\bscis\AppData\Local\Android\sdk\platform-tools>
working fine.....
This is an easy and quick solution when the string value is proper with the comma(,).
But if the string is with the last character with the comma, Which makes a blank array element, and this is also removed extra spaces around it.
"123,234,345,"
So I suggest using push()
var arr = [], str="123,234,345,"
str.split(",").map(function(item){
if(item.trim()!=''){arr.push(item.trim())}
})
In PHP, there is function srand(seed)
which generate fixed random value for particular seed.
But, in JS, there is no such inbuilt function.
However, we can write simple and short function.
Step 1: Choose some Seed (Fix Number).
var seed = 100;
Number should be Positive Integer and greater than 1, further explanation in Step 2.
Step 2: Perform Math.sin() function on Seed, it will give sin value of that number. Store this value in variable x.
var x;
x = Math.sin(seed); // Will Return Fractional Value between -1 & 1 (ex. 0.4059..)
sin() method returns a Fractional value between -1 and 1.
And we don't need Negative value, therefore, in first step choose number greater than 1.
Step 3: Returned Value is a Fractional value between -1 and 1.
So mulitply this value with 10 for making it more than 1.
x = x * 10; // 10 for Single Digit Number
Step 4: Multiply the value with 10 for additional digits
x = x * 10; // Will Give value between 10 and 99 OR
x = x * 100; // Will Give value between 100 and 999
Multiply as per requirement of digits.
The result will be in decimal.
Step 5: Remove value after Decimal Point by Math's Round (Math.round()) Method.
x = Math.round(x); // This will give Integer Value.
Step 6: Turn Negative Values into Positive (if any) by Math.abs method
x = Math.abs(x); // Convert Negative Values into Positive(if any)
Explanation End.
Final Code
var seed = 111; // Any Number greater than 1
var digit = 10 // 1 => single digit, 10 => 2 Digits, 100 => 3 Digits and so. (Multiple of 10)
var x; // Initialize the Value to store the result
x = Math.sin(seed); // Perform Mathematical Sin Method on Seed.
x = x * 10; // Convert that number into integer
x = x * digit; // Number of Digits to be included
x = Math.round(x); // Remove Decimals
x = Math.abs(x); // Convert Negative Number into Positive
Clean and Optimized Functional Code
function random_seed(seed, digit = 1) {
var x = Math.abs(Math.round(Math.sin(seed++) * 10 * digit));
return x;
}
Then Call this function using
random_seed(any_number, number_of_digits)
any_number is must and should be greater than 1.
number_of_digits is optional parameter and if nothing passed, 1 Digit will return.
random_seed(555); // 1 Digit
random_seed(234, 1); // 1 Digit
random_seed(7895656, 1000); // 4 Digit
Try evaluating the cell using LEN
. If it contains a formula LEN
will return 0
. If it contains text it will return greater than 0
.
Select * from table where date > 'Today's date(mm/dd/yyyy)'
You can also add time in the single quotes(00:00:00AM)
For example:
Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'
To execute your command directly from within C#, you would use the SqlCommand class.
Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName";
string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
In the future one would use left: unset;
for unsetting the value of left.
As of today 4 nov 2014 unset
is only supported in Firefox.
My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.
The first case is telling the web server that you are posting JSON data as in:
{ Name : 'John Smith', Age: 23}
The second option is telling the web server that you will be encoding the parameters in the URL as in:
Name=John+Smith&Age=23
In res/drawable
folder,
1. Create a new Drawable Resources
.
2. Input file name.
A new file will be created inside the res/drawable
folder.
Replace this code inside the newly created file and replace ic_action_back
with your drawable file name.
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/ic_action_back"
android:tint="@color/color_primary_text" />
Now, you can use it with Resource ID, R.id.filename
.
Imho this is not really possible. All posted solutions fails for strings like "test" and so on. If they can be divided through 4, are not null or empty, and if they are a valid base64 character, they will pass all tests. That can be many strings ...
So there is no real solution other than knowing that this is a base 64 encoded string. What I've come up with is this:
if (base64DecodedString.StartsWith("<xml>")
{
// This was really a base64 encoded string I was expecting. Yippie!
}
else
{
// This is gibberish.
}
I expect that the decoded string begins with a certain structure, so I check for that.
It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE
would have been too narrow in its meaning.
SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.
As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md
The following is taken from http://pandas.pydata.org/pandas-docs/dev/indexing.html. There are a few more examples... you have to scroll down a little
In [816]: df1
0 2 4 6
0 0.569605 0.875906 -2.211372 0.974466
2 -2.006747 -0.410001 -0.078638 0.545952
4 -1.219217 -1.226825 0.769804 -1.281247
6 -0.727707 -0.121306 -0.097883 0.695775
8 0.341734 0.959726 -1.110336 -0.619976
10 0.149748 -0.732339 0.687738 0.176444
Select via integer slicing
In [817]: df1.iloc[:3]
0 2 4 6
0 0.569605 0.875906 -2.211372 0.974466
2 -2.006747 -0.410001 -0.078638 0.545952
4 -1.219217 -1.226825 0.769804 -1.281247
In [818]: df1.iloc[1:5,2:4]
4 6
2 -0.078638 0.545952
4 0.769804 -1.281247
6 -0.097883 0.695775
8 -1.110336 -0.619976
Select via integer list
In [819]: df1.iloc[[1,3,5],[1,3]]
2 6
2 -0.410001 0.545952
6 -0.121306 0.695775
10 -0.732339 0.176444
Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp
Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp
Select DateAdd(Hour, 10 , JoiningDate )
from emp
Select dateadd (hour , 10 , getdate()), getdate()
Select dateadd (hour , 10 , joiningDate)
from Emp
Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate
From EMP
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
In case of using a configuration based on a YML file, the following will be the property that needs to be adjusted inside the given file:
*driverClassName: com.mysql.cj.jdbc.Driver*
As detailed in the Oracle Java SE Support Roadmap
After April 2015, Oracle will no longer post updates of Java SE 7 to its public download sites. Existing Java SE 7 downloads already posted as of April 2015 will remain accessible in the Java Archive
Check the Java SE 7 Archive Downloads page. The last release was update 80, therefore the 32-bit filename to download is jdk-7u80-windows-i586.exe
(64-bit is named jdk-7u80-windows-x64.exe
.
Old Java downloads also require a sign on to an Oracle account now :-( however with some crafty cookie creating one can use wget
to grab the file without signing in.
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-windows-i586.exe"
<ng-include src="'views/sidepanel.html'"></ng-include>
OR
<div ng-include="'views/sidepanel.html'"></div>
OR
<div ng-include src="'views/sidepanel.html'"></div>
Points To Remember:
--> No spaces in src
--> Remember to use single quotation in double quotation for src
Another open source tool for this is Cloud Query https://docs.cloudquery.io/
For anyone having this problem with newer versions of Eclipse, head over to Window
->Preferences
->Java
->Editor
->Content assist
->Advanced
and mark Java Proposals
and Chain Template Proposals
as active.
edit php.ini file and increase memory_limit value.
memory_limit=1G
will solve this issue.
If someone looks for this…
I wanted to rsync only specific files and folders and managed to do it with this command: rsync --include-from=rsync-files
With rsync-files:
my-dir/
my-file.txt
- /*
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace(strrev("/$find/"),strrev($replace),strrev($string),1);
echo strrev($result); //output: this is my world, not my farm
[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.
I have written more about this in a blog post: "ACID Does Not Make Sense".
http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html
[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf
First you have to run the mongod
command in your terminal. Make sure the command executes properly.
Then in a new terminal tab run the mongo
command.
Then open the Robomongo GUI and create a new connection with the default settings.
From mongodb.com:
NoSQL databases differ from older, relational technology in four main areas:
Data models: A NoSQL database lets you build an application without having to define the schema first unlike relational databases which make you define your schema before you can add any data to the system. No predefined schema makes NoSQL databases much easier to update as your data and requirements change.
Data structure: Relational databases were built in an era where data was fairly structured and clearly defined by their relationships. NoSQL databases are designed to handle unstructured data (e.g., texts, social media posts, video, email) which makes up much of the data that exists today.
Scaling: It’s much cheaper to scale a NoSQL database than a relational database because you can add capacity by scaling out over cheap, commodity servers. Relational databases, on the other hand, require a single server to host your entire database. To scale, you need to buy a bigger, more expensive server.
Development model: NoSQL databases are open source whereas relational databases typically are closed source with licensing fees baked into the use of their software. With NoSQL, you can get started on a project without any heavy investments in software fees upfront.
.NET 4.0 and above:
using System.Web.Security.AntiXss;
//...
var encoded = AntiXssEncoder.HtmlEncode("input", useNamedEntities: true);
Block - Element take complete width.All properties height , width, margin , padding work
Inline - element take height and width according to the content. Height , width , margin bottom and margin top do not work .Padding and left and right margin work. Example span and anchor.
Inline block - 1. Element don't take complete width, that is why it has *inline* in its name. All properties including height , width, margin top and margin bottom work on it. Which also work in block level element.That's why it has *block* in its name.
2015 Update
Now you can use DrawableCompat to tint all kind of drawables. For example:
Drawable progress = ratingBar.getProgressDrawable();
DrawableCompat.setTint(progress, Color.WHITE);
This is backwards compatible up to API 4
Just choose Grid system
and "responsive utilities"
it gives you this: http://jsfiddle.net/7LVzs/
https://golang.org/src/time/format.go specified
For parsing time 15
is used for Hours, 04
is used for minutes, 05
for seconds.
For parsing Date 11
, Jan
, January
is for months, 02
, Mon
, Monday
for Day of the month, 2006
for year and of course MST
for zone
But you can use this layout as well, which I find very simple. "Mon Jan 2 15:04:05 MST 2006"
const layout = "Mon Jan 2 15:04:05 MST 2006"
userTimeString := "Fri Dec 6 13:05:05 CET 2019"
t, _ := time.Parse(layout, userTimeString)
fmt.Println("Server: ", t.Format(time.RFC850))
//Server: Friday, 06-Dec-19 13:05:05 CET
mumbai, _ := time.LoadLocation("Asia/Kolkata")
mumbaiTime := t.In(mumbai)
fmt.Println("Mumbai: ", mumbaiTime.Format(time.RFC850))
//Mumbai: Friday, 06-Dec-19 18:35:05 IST
I like using fsockopen open for this.
Calling readOnly=false from readOnly=true doesn't work since the previous transaction continues.
In your example, the handle() method on your service layer is starting a new read-write transaction. If the handle method in turn calls service methods that annotated read-only, the read-only will take no effect as they will participate in the existing read-write transaction instead.
If it is essential for those methods to be read-only, then you can annotate them with Propagation.REQUIRES_NEW, and they will then start a new read-only transaction rather than participate in the existing read-write transaction.
Here is a worked example, CircuitStateRepository is a spring-data JPA repository.
BeanS calls a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.
31 09:39:44.199 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean 2 pariticipates in it.
31 09:39:44.230 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction
Nothing is committed to the database.
Now change Bean2 @Transactional
annotation to add propagation=Propagation.REQUIRES_NEW
Bean1 starts a read-only tx.
31 09:31:36.418 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean2 starts a new read-write tx
31 09:31:36.449 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [nz.co.vodafone.wcim.business.Bean2.createSomething]
And the changes made by Bean2 are now committed to the database.
Here's the example, tested with spring-data, hibernate and oracle.
@Named
public class BeanS {
@Inject
Bean1 bean1;
@Scheduled(fixedRate = 20000)
public void runSomething() {
bean1.startSomething();
}
}
@Named
@Transactional(readOnly = true)
public class Bean1 {
Logger log = LoggerFactory.getLogger(Bean1.class);
@Inject
private CircuitStateRepository csr;
@Inject
private Bean2 bean2;
public void startSomething() {
Iterable<CircuitState> s = csr.findAll();
CircuitState c = s.iterator().next();
log.info("GOT CIRCUIT {}", c.getCircuitId());
bean2.createSomething(c.getCircuitId());
}
}
@Named
@Transactional(readOnly = false)
public class Bean2 {
@Inject
CircuitStateRepository csr;
public void createSomething(String circuitId) {
CircuitState c = new CircuitState(circuitId + "-New-" + new DateTime().toString("hhmmss"), new DateTime());
csr.save(c);
}
}
Its actually very simple: simply Rotate the list view to lay on its side
mlistView.setRotation(-90);
Then upon inflating the children, that should be inside the getView method. you rotate the children to stand up straight:
mylistViewchild.setRotation(90);
Edit: if your ListView doesnt fit properly after rotation, place the ListView inside this RotateLayout like this:
<com.github.rongi.rotate_layout.layout.RotateLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:angle="90"> <!-- Specify rotate angle here -->
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</com.github.rongi.rotate_layout.layout.RotateLayout>
The simplest way to get this is on an Excel file. Let’s say for example that you have two numbers, 5 and 2 in cells A1 and B1 accordingly, and you want to find their sum in a third cell, let's say A2. You can do this in two ways.
Either by passing their values to cell A2 by typing = 5 + 2 into this cell. In this case, if the values of the cells A1 or B1 change, the sum in A2 remains the same.
Or by passing the “references” of the cells A1 and B1 to cell A2 by typing = A1 + B1. In this case, if the values of the cells A1 or B1 change, the sum in A2 changes too.
I had this problem after installing Crystal Reports for Visual Studio. I solved it by closing all Visual Studio instances and reinstalling Crystal Reports.
From the official document:
"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)
When you see this notification, it indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:
cat /proc/sys/fs/inotify/max_user_watches
The limit can be increased to its maximum by editing
/etc/sysctl.conf
and adding this line to the end of the file:
fs.inotify.max_user_watches=524288
The new value can then be loaded in by running
sudo sysctl -p
Note that Arch Linux works a little differently, See Increasing the amount of inotify watchers for details.
While 524,288 is the maximum number of files that can be watched, if you're in an environment that is particularly memory constrained, you may wish to lower the number. Each file watch takes up 540 bytes (32-bit) or ~1kB (64-bit), so assuming that all 524,288 watches are consumed, that results in an upper bound of around 256MB (32-bit) or 512MB (64-bit).
Another option
is to exclude specific workspace directories from the VS Code file watcher with the files.watcherExclude setting. The default for files.watcherExclude excludes node_modules and some folders under .git, but you can add other directories that you don't want VS Code to track.
"files.watcherExclude": {
"**/.git/objects/**": true,
"**/.git/subtree-cache/**": true,
"**/node_modules/*/**": true
}
the easiest way to do this is to wrap your sockets in ObjectInput/OutputStreams and send serialized java objects. you can create classes which contain the relevant data, and then you don't need to worry about the nitty gritty details of handling binary protocols. just make sure that you flush your object streams after you write each object "message".
So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.
The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.
This helped me change my code, and I now have it working. - Thanks for your comments.
My implementation ended up looking like this;
I require my routes in the app.js:
var express = require('express')
, site = require('./site')
, wiki = require('./wiki');
And I add my routes like this:
app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);
I have two files called wiki.js and site.js in the root of my app, containing this:
exports.edit = function(req, res) {
var wiki_entry = req.params.id;
res.render('wiki/edit', {
title: 'Editing Wiki',
wiki: wiki_entry
})
}
Since version 1.2, Django has QuerySet.exists() method which is the most efficient:
if orgs.exists():
# Do this...
else:
# Do that...
But if you are going to evaluate QuerySet anyway it's better to use:
if orgs:
...
For more information read QuerySet.exists() documentation.
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
There are some issues with building protobuf 2.4.1 from source on a Mac. There is a patch that also has to be applied. All this is contained within the homebrew protobuf241 formula, so I would advise using it.
To install protocol buffer version 2.4.1 type the following into a terminal:
brew tap homebrew/versions
brew install protobuf241
If you already have a protocol buffer version that you tried to install from source, you can type the following into a terminal to have the source code overwritten by the homebrew version:
brew link --force --overwrite protobuf241
Check that you now have the correct version installed by typing:
protoc --version
It should display 2.4.1
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client
.
You could try to run the 2to3
tool on your code, and try to have it translated automatically. References to httplib
will automatically be rewritten to use http.client
instead.
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
If you need the index of the item you're working with then using a foreach
loop is the wrong method of iterating over the collection. Change the way you're looping so you have the index:
for(int i = 0; i < dt.Rows.Count; i++)
{
// your index is in i
var row = dt.Rows[i];
}
You can create tags for GitHub by either using:
To create a tag on your current branch, run this:
git tag <tagname>
If you want to include a description with your tag, add -a
to create an annotated tag:
git tag <tagname> -a
This will create a local
tag with the current state of the branch you are on. When pushing to your remote repo, tags are NOT included by default. You will need to explicitly say that you want to push your tags to your remote repo:
git push origin --tags
From the official Linux Kernel Git documentation for git push
:
--tags
All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.
Or if you just want to push a single tag:
git push origin <tag>
See also my answer to How do you push a tag to a remote repository using Git? for more details about that syntax above.
You can find GitHub's instructions for this at their Creating Releases help page. Here is a summary:
Click the releases link on our repository page,
Click on Create a new release or Draft a new release,
Fill out the form fields, then click Publish release at the bottom,
After you create your tag on GitHub, you might want to fetch it into your local repository too:
git fetch
Now next time, you may want to create one more tag within the same release from website. For that follow these steps:
Go to release tab
Click on edit button for the release
Provide name of the new tag ABC_DEF_V_5_3_T_2 and hit tab
After hitting tab, UI will show this message: Excellent! This tag will be created from the target when you publish this release. Also UI will provide an option to select the branch/commit
Select branch or commit
Check "This is a pre-release" checkbox for qa tag and uncheck it if the tag is created for Prod tag.
After that click on "Update Release"
This will create a new Tag within the existing Release.
SELECT SUM(No), HOUR(dateofissue)
FROM tablename
WHERE dateofissue>='2011-07-30'
GROUP BY HOUR(dateofissue)
It will give the hour by sum from a particular day!
For those who reached here searching if they could undo git clean -f -d
, by which a file created in eclipse was deleted,
You can do the same from the UI using "restore from local history" for ref:Restore from local history
The trailing slash does not matter for your root domain or subdomain. Google sees the two as equivalent.
But trailing slashes do matter for everything else because Google sees the two versions (one with a trailing slash and one without) as being different URLs. Conventionally, a trailing slash (/) at the end of a URL meant that the URL was a folder or directory.
A URL without a trailing slash at the end used to mean that the URL was a file.
You need to get a reference of your form, and after that you can iterate the elements
collection. So, assuming for instance:
<form method="POST" action="submit.php" id="my-form">
..etc..
</form>
You will have something like:
var elements = document.getElementById("my-form").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.type === "text" && element.value === "")
console.log("it's an empty textfield")
}
Notice that in browser that would support querySelectorAll you can also do something like:
var elements = document.querySelectorAll("#my-form input[type=text][value='']")
And you will have in elements
just the element that have an empty value attribute. Notice however that if the value is changed by the user, the attribute will be remain the same, so this code is only to filter by attribute not by the object's property. Of course, you can also mix the two solution:
var elements = document.querySelectorAll("#my-form input[type=text]")
for (var i = 0, element; element = elements[i++];) {
if (element.value === "")
console.log("it's an empty textfield")
}
You will basically save one check.
If you don't want use ngOnChange
implement og onChange()
method, you can also subscribe to changes of a specific item by valueChanges
event, ETC.
myForm = new FormGroup({
first: new FormControl(),
});
this.myForm.valueChanges.subscribe((formValue) => {
this.changeDetector.markForCheck();
});
the markForCheck()
writen because of using in this declare:
changeDetection: ChangeDetectionStrategy.OnPush
Inside file strings.xml
define a String resource like this:
<string name="string_to_format">Amount: %1$f for %2$d days%3$s</string>
Inside your code (assume it inherits from Context) simply do the following:
String formattedString = getString(R.string.string_to_format, floatVar, decimalVar, stringVar);
(In comparison to the answer from LocalPCGuy or Giovanny Farto M. the String.format method is not needed.)
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
In my case, this exception was being caused by an unsecure ajax call on an SSL enabled site. Specifically: my url was 'http://...'
instead of 'https://...'
. I just replaced it with '//...'
.
To me, the error was misleading, and hopefully this may help anyone landing here after searching for the same error.
file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
any_string = "Hello\nWorld"
file.write(any_string)
file.close()
button:hover is just when you move the cursor over the button.
Try button:active instead...will work for other elements as well
button:active{_x000D_
color: red;_x000D_
}
_x000D_
You didn't do what you're being asked to do.
What is asked:
I have to execute ../gradlew build
What you do
cd ..
gradlew build
That's not the same thing.
The first one will use the gradlew command found in the ..
directory (mdeinum...
), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore
.
The second one will execute the gradlew command found in the current directory (mdeinum...
), and look for the build file to execute in the current directory, which is mdeinum...
.
So the build file executed is not the same.
As said already in the comments you can use the csv
library in python. csv means comma separated values which seems exactly your case: a label and a value separated by a comma.
Being a category and value type I would rather use a dictionary type instead of a list of tuples.
Anyway in the code below I show both ways: d
is the dictionary and l
is the list of tuples.
import csv
file_name = "test.txt"
try:
csvfile = open(file_name, 'rt')
except:
print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l = list()
for row in csvReader:
d[row[1]] = row[0]
l.append((row[0], row[1]))
print(d)
print(l)
Insert into TBL (Name, UserName, Password) Output Inserted.IdentityColumnName
Values ('example', 'example', 'example')
(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)
You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.
Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:
telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)
You should get a response like:
250 2.0.0 Ok: queued as 6E414C4643A
The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:
sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected] [email protected]
[email protected] [email protected]
@localdomain.local [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the
generic file)
Happy Trails
Java Object Serialization
Serialization
is a mechanism to transform a graph of Java objects into an array of bytes for storage(to disk file
) or transmission(across a network
), then by using deserialization we can restore the graph of objects.
Graphs of objects are restored correctly using a reference sharing mechanism. But before storing, check whether serialVersionUID from input-file/network and .class file serialVersionUID are the same. If not, throw a java.io.InvalidClassException
.
Each versioned class must identify the original class version for which it is capable of writing streams and from which it can read. For example, a versioned class must declare:
serialVersionUID Syntax
// ANY-ACCESS-MODIFIER static final long serialVersionUID = (64-bit has)L; private static final long serialVersionUID = 3487495895819393L;
serialVersionUID is essential to the serialization process. But it is optional for the developer to add it into the java source file. If a serialVersionUID is not included, the serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.
Note - It is strongly recommended that all serializable classes explicitly declare a serialVersionUID, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations
, and can thus result in unexpected serialVersionUID conflicts during deserialization, causing deserialization to fail.
Inspecting Serializable Classes
A Java object is only serializable. if a class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable.
A class must implement java.io.Serializable interface in order to serialize its object successfully. Serializable is a marker interface and used to inform the compiler that the class implementing it has to be added serializable behavior. Here Java Virtual Machine (JVM) is responsible for its automatic serialization.
transient Keyword:
java.io.Serializable interface
While serializing an object, if we don't want certain data members of the object to be serialized we can use the transient modifier. The transient keyword will prevent that data member from being serialized.
- Fields declared as transient or static are ignored by the serialization process.
+--------------+--------+-------------------------------------+ | Flag Name | Value | Interpretation | +--------------+--------+-------------------------------------+ | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.| +--------------+--------+-------------------------------------+ |ACC_TRANSIENT | 0x0080 | Declared transient; not written or | | | | read by a persistent object manager.| +--------------+--------+-------------------------------------+
class Employee implements Serializable {
private static final long serialVersionUID = 2L;
static int id;
int eno;
String name;
transient String password; // Using transient keyword means its not going to be Serialized.
}
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
class Emp implements Externalizable {
int eno;
String name;
transient String password; // No use of transient, we need to take care of write and read.
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(eno);
out.writeUTF(name);
//out.writeUTF(password);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.eno = in.readInt();
this.name = in.readUTF();
//this.password = in.readUTF(); // java.io.EOFException
}
}
Only objects that support the java.io.Serializable or java.io.Externalizable interface can be written to
/read from
streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.
Serializable Example For Files
public class SerializationDemo {
static String fileName = "D:/serializable_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Employee emp = new Employee( );
Employee.id = 1; // Can not Serialize Class data.
emp.eno = 77;
emp.name = "Yash";
emp.password = "confidential";
objects_WriteRead(emp, fileName);
Emp e = new Emp( );
e.eno = 77;
e.name = "Yash";
e.password = "confidential";
objects_WriteRead_External(e, fileName);
/*String stubHost = "127.0.0.1";
Integer anyFreePort = 7777;
socketRead(anyFreePort); //Thread1
socketWrite(emp, stubHost, anyFreePort); //Thread2*/
}
public static void objects_WriteRead( Employee obj, String serFilename ) throws IOException{
FileOutputStream fos = new FileOutputStream( new File( serFilename ) );
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
objectOut.writeObject( obj );
objectOut.close();
fos.close();
System.out.println("Data Stored in to a file");
try {
FileInputStream fis = new FileInputStream( new File( serFilename ) );
ObjectInputStream ois = new ObjectInputStream( fis );
Object readObject;
readObject = ois.readObject();
String calssName = readObject.getClass().getName();
System.out.println("Restoring Class Name : "+ calssName); // InvalidClassException
Employee emp = (Employee) readObject;
System.out.format("Obj[No:%s, Name:%s, Pass:%s]", emp.eno, emp.name, emp.password);
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void objects_WriteRead_External( Emp obj, String serFilename ) throws IOException {
FileOutputStream fos = new FileOutputStream(new File( serFilename ));
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
obj.writeExternal( objectOut );
objectOut.flush();
fos.close();
System.out.println("Data Stored in to a file");
try {
// create a new instance and read the assign the contents from stream.
Emp emp = new Emp();
FileInputStream fis = new FileInputStream(new File( serFilename ));
ObjectInputStream ois = new ObjectInputStream( fis );
emp.readExternal(ois);
System.out.format("Obj[No:%s, Name:%s, Pass:%s]", emp.eno, emp.name, emp.password);
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Serializable Example Over Network
Distributing object's state across different address spaces, either in different processes on the same computer, or even in multiple computers connected via a network, but which work together by sharing data and invoking methods.
/**
* Creates a stream socket and connects it to the specified port number on the named host.
*/
public static void socketWrite(Employee objectToSend, String stubHost, Integer anyFreePort) {
try { // CLIENT - Stub[marshalling]
Socket client = new Socket(stubHost, anyFreePort);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(objectToSend);
out.flush();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates a server socket, bound to the specified port.
public static void socketRead( Integer anyFreePort ) {
try { // SERVER - Stub[unmarshalling ]
ServerSocket serverSocket = new ServerSocket( anyFreePort );
System.out.println("Server serves on port and waiting for a client to communicate");
/*System.in.read();
System.in.read();*/
Socket socket = serverSocket.accept();
System.out.println("Client request to communicate on port server accepts it.");
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Employee objectReceived = (Employee) in.readObject();
System.out.println("Server Obj : "+ objectReceived.name );
socket.close();
serverSocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
@see
This is really just an expansion on @mjolinor simple answer [Use Task Scheduler].
I knew "Task Scheduler" was the correct way, but it took a bit of effort to get it running the way I wanted and thought I'd post my finding for others.
Issues including:
Note: You must have permission to run script see ExecutionPolicy
Then in Task Scheduler, the most important/tricky part is the Action
It should be Start a Program
Program/Script:
powershell
Add arguments (optional) :
-windowstyle hidden -command full\path\script.ps1 >> "%TEMP%\StartupLog.txt" 2>&1
Note:
If you see -File
on the internet, it will work, but understand nothing can be after -File
except the File Path, IE: The redirect is taken to be part of the file path and it fails, you must use -command
in conjunction with redirect, but you can prepend additional commands/arguments such as -windowstyle hidden
to not show PowerShell window.
I had to adjust all Write-Host
to Write-Output
in my script as well.
Set title color
for different states:
@IBOutlet weak var loginButton: UIButton! {
didSet {
loginButton.setTitleColor(UIColor.init(white: 1, alpha: 0.3), for: .disabled)
loginButton.setTitleColor(UIColor.init(white: 1, alpha: 1), for: .normal)
}
}
Usage: (text color will get change automatically)
loginButton.isEnabled = false
public class ArrayDuplicate {
private static Scanner sc;
static int totalCount = 0;
public static void main(String[] args) {
int n, num;
sc = new Scanner(System.in);
System.out.print("Enter the size of array: ");
n =sc.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++){
System.out.print("Enter the element at position "+i+": ");
num = sc.nextInt();
a[enter image description here][1][i]=num;
}
System.out.print("Elements in array are: ");
for(int i=0;i<a.length;i++)
System.out.print(a[i]+" ");
System.out.println();
duplicate(a);
System.out.println("There are "+totalCount+" repeated numbers:");
}
public static void duplicate(int[] a){
int j = 0,count, recount, temp;
for(int i=0; i<a.length;i++){
count = 0;
recount = 0;
j=i+1;
while(j<a.length){
if(a[i]==a[j])
count++;
j++;
}
if(count>0){
temp = a[i];
for(int x=0;x<i;x++){
if(a[x]==temp)
recount++;
}
if(recount==0){
totalCount++;
System.out.println(+a[i]+" : "+count+" times");
}
}
}
}
}
"success" : function(data){
//do stuff here
fnCallback(data);
}
Strings, though they are not set
types, have a valuable in
property during validation in scripts:
yn = input("Are you sure you want to do this? ")
if yn in "yes":
#accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes'
return True
return False
I hope this helps you better understand the use of in
with this example.
You can use JS as below:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('elementid').focus();");
It sounds like you're trying to link with your resulting object file with gcc
instead of g++
:
Note that programs using C++ object files must always be linked with g++, in order to supply the appropriate C++ libraries. Attempting to link a C++ object file with the C compiler gcc will cause "undefined reference" errors for C++ standard library functions:
$ g++ -Wall -c hello.cc
$ gcc hello.o (should use g++)
hello.o: In function `main':
hello.o(.text+0x1b): undefined reference to `std::cout'
.....
hello.o(.eh_frame+0x11):
undefined reference to `__gxx_personality_v0'
Source: An Introduction to GCC - for the GNU compilers gcc and g++
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
Oh, just with this:
$ docker-compose up client server database
You can use the DataFrame apply
method:
order_df['Value'] = order_df.apply(lambda row: (row['Prices']*row['Amount']
if row['Action']=='Sell'
else -row['Prices']*row['Amount']),
axis=1)
It is usually faster to use these methods rather than over for loops.
I think this is the most simple answer. Please verify that it works:
StackFullView.layer.isHidden = true
Task_TopSpaceSections.constant = 0. //your constraint of top view
check here https://www.youtube.com/watch?v=EBulMWMoFuw
Try:
$("#"+styleTarget).css({ 'font-size': $(this).val() });
By putting the value in quotes, it becomes a string, and "+$(this).val()+"px
is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:
Using a map:
$("#elem").css({
fontSize: 20
});
Using key and value parameters:
All of these are valid.
$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");
You can replace "fontSize"
with "font-size"
but it will have to be quoted then.
This isn't a bad structure; it will work just fine. However, you do have to have functions in a function to do commands when someone clicks on a button or something
So what you could do is write classes for these then have methods in the class that handle commands for the button clicks and such.
Here's an example:
import tkinter as tk
class Window1:
def __init__(self, master):
pass
# Create labels, entries,buttons
def button_click(self):
pass
# If button is clicked, run this method and open window 2
class Window2:
def __init__(self, master):
#create buttons,entries,etc
def button_method(self):
#run this when button click to close window
self.master.destroy()
def main(): #run mianloop
root = tk.Tk()
app = Window1(root)
root.mainloop()
if __name__ == '__main__':
main()
Usually tk programs with multiple windows are multiple big classes and in the __init__
all the entries, labels etc are created and then each method is to handle button click events
There isn't really a right way to do it, whatever works for you and gets the job done as long as its readable and you can easily explain it because if you cant easily explain your program, there probably is a better way to do it.
Take a look at Thinking in Tkinter.
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
My Answer: All of the following should be overridden (i.e. describe them all within columndefinition
, if appropriate):
length
precision
scale
nullable
unique
i.e. the column DDL will consist of: name
+ columndefinition
and nothing else.
Rationale follows.
Annotation containing the word "Column" or "Table" is purely physical - properties only used to control DDL/DML against database.
Other annotation purely logical - properties used in-memory in java to control JPA processing.
That's why sometimes it appears the optionality/nullability is set twice - once via @Basic(...,optional=true)
and once via @Column(...,nullable=true)
. Former says attribute/association can be null in the JPA object model (in-memory), at flush time; latter says DB column can be null. Usually you'd want them set the same - but not always, depending on how the DB tables are setup and reused.
In your example, length and nullable properties are overridden and redundant.
So, when specifying columnDefinition, what other properties of @Column are made redundant?
In JPA Spec & javadoc:
columnDefinition
definition:
The SQL fragment that is used when generating the DDL for the column.
columnDefinition
default:
Generated SQL to create a column of the inferred type.
The following examples are provided:
@Column(name="DESC", columnDefinition="CLOB NOT NULL", table="EMP_DETAIL")
@Column(name="EMP_PIC", columnDefinition="BLOB NOT NULL")
And, err..., that's it really. :-$ ?!
Does columnDefinition override other properties provided in the same annotation?
The javadoc and JPA spec don't explicity address this - spec's not giving great protection. To be 100% sure, test with your chosen implementation.
The following can be safely implied from examples provided in the JPA spec
name
& table
can be used in conjunction with columnDefinition
, neither are overriddennullable
is overridden/made redundant by columnDefinition
The following can be fairly safely implied from the "logic of the situation" (did I just say that?? :-P ):
length
, precision
, scale
are overridden/made redundant by the columnDefinition
- they are integral to the typeinsertable
and updateable
are provided separately and never included in columnDefinition
, because they control SQL generation in-memory, before it is emmitted to the database.That leaves just the "unique
" property. It's similar to nullable - extends/qualifies the type definition, so should be treated integral to type definition. i.e. should be overridden.
Test My Answer For columns "A" & "B", respectively:
@Column(name="...", table="...", insertable=true, updateable=false,
columndefinition="NUMBER(5,2) NOT NULL UNIQUE"
@Column(name="...", table="...", insertable=false, updateable=true,
columndefinition="NVARCHAR2(100) NULL"
Parameter int defStyleAttr
does not specifies the style. From the Android documentation:
defStyleAttr - An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
To setup the style in View constructor we have 2 possible solutions:
With use of ContextThemeWrapper:
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
TextView textView = new TextView(wrappedContext, null, 0);
With four-argument constructor (available starting from LOLLIPOP):
TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
Key thing for both solutions - defStyleAttr
parameter should be 0 to apply our style to the view.
You can achieve what you want by defining a footer for the tableview. See this answer for more details:Eliminate Extra separators below UITableView
STATICFILES_DIRS
: You can keep the static files for your project here e.g. the ones used by your templates.
STATIC_ROOT
: leave this empty, when you do manage.py collectstatic
, it will search for all the static files on your system and move them here. Your static file server is supposed to be mapped to this folder wherever it is located. Check it after running collectstatic and you'll find the directory structure django has built.
--------Edit----------------
As pointed out by @DarkCygnus, STATIC_ROOT should point at a directory on your filesystem, the folder should be empty since it will be populated by Django.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
or
STATIC_ROOT = '/opt/web/project/static_files'
--------End Edit -----------------
STATIC_URL
: '/static/' is usually fine, it's just a prefix for static files.
This is the one that worked for my case on my current machine (git bash on windows 7):
find ./ -type f -iname "*.cs" -print0 | xargs -0 grep "content pattern"
I always forget the -print0 and -0 for paths with spaces.
EDIT: My preferred tool is now instead ripgrep: https://github.com/BurntSushi/ripgrep/releases . It's really fast and has better defaults (like recursive by default). Same example as my original answer but using ripgrep: rg -g "*.cs" "content pattern"
If you really want a thematic break, by all means use the <hr>
tag.
If you just want a design line, you could use something like the css class
.hline-bottom {
padding-bottom: 10px;
border-bottom: 2px solid #000; /* whichever color you prefer */
}
and use it like
<div class="block_1 hline-bottom">Cheese</div>
You could follow these steps when you stumble upon this issue:
git remote show origin
which outputs this:
remote origin Fetch URL: <your_git_path> Push URL: <your_git_path> HEAD branch: development Remote branches: development tracked Feature2 tracked master tracked refs/remotes/origin/Feature1 stale (use 'git remote prune' to remove) Local branches configured for 'git pull': Feature2 merges with remote Feature2 development merges with remote development master merges with remote master Local refs configured for 'git push': Feature2 pushes to Feature2 (up to date) development pushes to development (up to date) master pushes to master (local out of date)
» git remote update Fetching origin From gitlab.domain.local:ProjectGroupName/ProjectName * [new branch] Feature3 -> Feature3
As you can see the new branch has been fetched from remote.
3. Finally, checkout the branch with this command
» git checkout -b Feature3 origin/Feature3 Branch Feature3 set up to track remote branch Feature3 from origin. Switched to a new branch 'Feature3'
It is not necessary to explicitly tell Git to track(using --track) the branch with remote.
The above command will set the local branch to track the remote branch from origin.