Checking for empty string if it is equal to null, length is zero or containing "null" string
public static boolean isEmptyString(String text) {
return (text == null || text.trim().equals("null") || text.trim()
.length() <= 0);
}
An example:
eventcreate /ID 1 /L APPLICATION /T INFORMATION /SO MYEVENTSOURCE /D "My first log"
This will create a new event source named MYEVENTSOURCE
under APPLICATION
event log as INFORMATION
event type.
I think this utility is included only from XP onwards.
Windows IT Pro: JSI Tip 5487. Windows XP includes the EventCreate utility for creating custom events.
Type eventcreate /?
in CMD prompt
Microsoft TechNet: Windows Command-Line Reference: Eventcreate
SS64: Windows Command-Line Reference: Eventcreate
If you want to exclude the sample controller's sample action
class TestController < ApplicationController
protect_from_forgery :except => [:sample]
def sample
render json: @hogehoge
end
end
You can to process requests from outside without any problems.
You can also use : mysql> select user,host from mysql.user;
+---------------+-------------------------------+
| user | host |
+---------------+-------------------------------+
| fkernel | % |
| nagios | % |
| readonly | % |
| replicant | % |
| reporting | % |
| reporting_ro | % |
| nagios | xx.xx.xx.xx |
| haproxy_root | xx.xx.xx.xx
| root | 127.0.0.1 |
| nagios | localhost |
| root | localhost |
+---------------+-------------------------------+
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
You can do This.
final List<String> fruits_list = new ArrayList<String>(Arrays.asList(fruits));
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, fruits_list){
@Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
if(position %2 == 1)
{
// Set a background color for ListView regular row/item
view.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return view;
}
};
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
}
}
Call label.Invalidate
and then label.Update()
- usually the update only happens after you exit the current function but calling Update forces it to update at that specific place in code.
From MSDN:
The Invalidate method governs what gets painted or repainted. The Update method governs when the painting or repainting occurs. If you use the Invalidate and Update methods together rather than calling Refresh, what gets repainted depends on which overload of Invalidate you use. The Update method just forces the control to be painted immediately, but the Invalidate method governs what gets painted when you call the Update method.
In C char
gets promoted to int
in expressions. That pretty much explains every question, if you think about it.
Source: The C Programming Language by Brian W.Kernighan and Dennis M.Ritchie
A must read if you want to learn C.
Also see this stack overflow page, where people much more experienced then me can explain it much better then I ever can.
If you want to add a default value for the already created column, this works for me:
ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure
Use a generic object and map key value pairs to it.
$oVal = new stdClass();
$oVal->key = $value
Or cast an array into an object
$aVal = array( 'key'=>'value' );
$oVal = (object) $aVal;
As mentioned on the javadocs you are better off using a ScheduledThreadPoolExecutor.
Use this class when your use case requires multiple worker threads and the sleep interval is small. How small ? Well, I'd say about 15 minutes. The AlarmManager
starts schedule intervals at this time and it seems to suggest that for smaller sleep intervals this class can be used. I do not have data to back the last statement. It is a hunch.
Your service can be closed any time by the VM. Do not use services for recurring tasks. A recurring task can start a service, which is another matter entirely.
For longer sleep intervals (>15 minutes), this is the way to go. AlarmManager
already has constants ( AlarmManager.INTERVAL_DAY
) suggesting that it can trigger tasks several days after it has initially been scheduled. It can also wake up the CPU to run your code.
You should use one of those solutions based on your timing and worker thread needs.
Referencing means taking the address of an existing variable (using &) to set a pointer variable. In order to be valid, a pointer has to be set to the address of a variable of the same type as the pointer, without the asterisk:
int c1;
int* p1;
c1 = 5;
p1 = &c1;
//p1 references c1
Dereferencing a pointer means using the * operator (asterisk character) to retrieve the value from the memory address that is pointed by the pointer: NOTE: The value stored at the address of the pointer must be a value OF THE SAME TYPE as the type of variable the pointer "points" to, but there is no guarantee this is the case unless the pointer was set correctly. The type of variable the pointer points to is the type less the outermost asterisk.
int n1;
n1 = *p1;
Invalid dereferencing may or may not cause crashes:
Invalid referencing is more likely to cause compiler errors than crashes, but it's not a good idea to rely on the compiler for this.
References:
http://www.codingunit.com/cplusplus-tutorial-pointers-reference-and-dereference-operators
& is the reference operator and can be read as “address of”.
* is the dereference operator and can be read as “value pointed by”.
http://www.cplusplus.com/doc/tutorial/pointers/
& is the reference operator
* is the dereference operator
http://en.wikipedia.org/wiki/Dereference_operator
The dereference operator * is also called the indirection operator.
try this
combobox.SelectedIndex = BindingSource.Item(9) where "9 = colum name 9 from table"
var timeConvert = function(n){
var minutes = n%60
var hours = (n - minutes) / 60
console.log(hours + ":" + minutes)
}
timeConvert(65)
this will log 1:5 to the console. It is a short and simple solution that should be easy to understand and no jquery plugin is necessary...
Maybe an old thread, but this code might be useful to visitors who want to create without regex
def listToString(s):
# initialize an empty string
str1 = ""
# return string
return (str1.join(s))
r = "Hello! How are you? *Smiling_Face* *Heart* erwer"
r1 = list(r)
i = 0
r2 = list()
start = True
for string in r1:
if string == "*":
if(start):
start = False
else:
start = True
else:
if(start):
r2.append(string)
else:
print("skipped" + string)
print(listToString(r2))
It means the class is not yet added to the repository.
If your project was checked-out (most probably a CVS project) and you added a new class file, it will have the ? icon.
For other CVS Label Decorations, check http://help.eclipse.org/help33/index.jsp?topic=/org.eclipse.platform.doc.user/reference/ref-cvs-decorations.htm
I just put --password
flag into my command and after hitting Enter it asked me for password, which I supplied.
select t.data_type
from user_tab_columns t
where t.TABLE_NAME = 'xxx'
and t.COLUMN_NAME='aaa'
Nuget's Automatic Package Restore is a feature of the Visual Studio (starting in 2013), not MSBuild. You'll have to run nuget.exe restore
if you want to restore packages from the command line.
You can also use the Enable Nuget Package Restore feature, but this is no longer recommended by the nuget folks because it makes intrusive changes to the project files and may cause problems if you build those projects in another solution.
When using a <select>
tag that shows all options, here's a work around using <div>
instead:
HTML
<div id='sectionOptionsSelect' size='5' class='block1'
style='visibility: hidden; border: 1px solid gray; padding: 5px; '>
<span class='addPageBreakAbove'>Add Page Break Above</span>
<span class='addPageBreakBelow'>Add Page Break Below</span>
<span class='removeSection'>
<label class='fa fa-window-close'
style='font-size: 25px; color: red; background: white; '></label>
Remove Section</span>
</div>
Supporting JS
$('#sectionOptionsSelect span').hover(function () {
$(this).css('background', '#c0ec67');
}, function () {
$(this).css('background', 'transparent');
});
$('.removeSection').click(function () {
alert('removeSection');
});
CSS
#sectionOptionsSelect span {
display: block;
}
check your casing, the name is typically stored in upper case
SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;
You can do that in this way:
ORDER BY `products`.`product_category_id` DESC ,`naam` ASC
Have a look at ORDER BY
Optimization
in your dispatcher servlet context xml, you have to add a propertie
"<property name="contentType" value="text/html;charset=UTF-8" />"
on your viewResolver bean.
we are using freemarker for views.
it looks something like this:
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
...
<property name="contentType" value="text/html;charset=UTF-8" />
...
</bean>
The AJAX request never has the opportunity to NOT follow the redirect (i.e., it must follow the redirect). More information can be found in this answer https://stackoverflow.com/a/2573589/965648
you can | for set union and & for set intersection.
for example:
set1={1,2,3}
set2={3,4,5}
print(set1&set2)
output=3
set1={1,2,3}
set2={3,4,5}
print(set1|set2)
output=1,2,3,4,5
curly braces in the answer.
You can also dump elasticsearch data in JSON format by http request:
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html
CURL -XPOST 'https://ES/INDEX/_search?scroll=10m'
CURL -XPOST 'https://ES/_search/scroll' -d '{"scroll": "10m", "scroll_id": "ID"}'
I could not get IE8+ to work by adding a jQuery event handler to the file input type. I had to go old-school and add the the onchange=""
attribute to the input tag:
<input type='file' onchange='getFilename(this)'/>
function getFileName(elm) {
var fn = $(elm).val();
....
}
EDIT:
function getFileName(elm) {
var fn = $(elm).val();
var filename = fn.match(/[^\\/]*$/)[0]; // remove C:\fakename
alert(filename);
}
you can also use iloc:
df.iloc[[1,3],:]
This will not work if the indexes in your dataframe do not correspond to the order of the rows due to prior computations. In that case use:
df.index.isin([1,3])
... as suggested in other responses.
It seems, that the simple way
-Dmaven.javadoc.skip=true
does not work with the release-plugin. in this case you have to pass the parameter as an "argument"
mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"
It is actually possible.
See: CSS Tip: How to Make Circles Without Images. See demo.
But be warned, It has serious disadvantages in terms of compatibility basically, you are making a cat bark.
See it working here
As you will see you just have to set up the height
and width
to half the border-radius
Good luck!
Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.
Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:
And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.
The problem lies in your base case.
"The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only a node (the root) has a height of zero." - Wikipedia
If there is no node, you want to return -1 not 0. This is because you are adding 1 at the end.
So if there isn't a node, you return -1 which cancels out the +1.
int findHeight(TreeNode<T> aNode) {
if (aNode == null) {
return -1;
}
int lefth = findHeight(aNode.left);
int righth = findHeight(aNode.right);
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
I don't know if I'm the one that doesn't get the question right, but this just worked for me: Using an onchange() event in your html, eg.
<select id="numberToSelect" onchange="selectNum">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
//javascript
function sele(){
var strUser = numberToSelect.value;
}
This will give you whatever value is on the select dropdown per click
One difference, that can be an advantage, is that if we are looking for a key that doesn't exist we will get None, not like when we use the brackets notation, in which case we will get an error thrown:
print(dictionary.get("address")) # None
print(dictionary["address"]) # throws KeyError: 'address'
Last thing that is cool about the get method, is that it receives an additional optional argument for a default value, that is if we tried to get the score value of a student, but the student doesn't have a score key we can get a 0 instead.
So instead of doing this (or something similar):
score = None
try:
score = dictionary["score"]
except KeyError:
score = 0
We can do this:
score = dictionary.get("score", 0)
# score = 0
If you're using IPython, you can simply run:
%load path/to/your/file.py
See http://ipython.org/ipython-doc/rel-1.1.0/interactive/tutorial.html
It is very simple.
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by Belal on 9/14/2017.
*/
//we need to extend the ArrayAdapter class as we are building an adapter
public class MyListAdapter extends ArrayAdapter<Hero> {
//the list values in the List of type hero
List<Hero> heroList;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public MyListAdapter(Context context, int resource, List<Hero> heroList) {
super(context, resource, heroList);
this.context = context;
this.resource = resource;
this.heroList = heroList;
}
//this will return the ListView Item as a View
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//we need to get the view of the xml for our list item
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
//getting the view
View view = layoutInflater.inflate(resource, null, false);
//getting the view elements of the list from the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textViewName = view.findViewById(R.id.textViewName);
TextView textViewTeam = view.findViewById(R.id.textViewTeam);
Button buttonDelete = view.findViewById(R.id.buttonDelete);
//getting the hero of the specified position
Hero hero = heroList.get(position);
//adding values to the list item
imageView.setImageDrawable(context.getResources().getDrawable(hero.getImage()));
textViewName.setText(hero.getName());
textViewTeam.setText(hero.getTeam());
//adding a click listener to the button to remove item from the list
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//we will call this method to remove the selected value from the list
//we are passing the position which is to be removed in the method
removeHero(position);
}
});
//finally returning the view
return view;
}
//this method will remove the item from the list
private void removeHero(final int position) {
//Creating an alert dialog to confirm the deletion
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to delete this?");
//if the response is positive in the alert
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//removing the item
heroList.remove(position);
//reloading the list
notifyDataSetChanged();
}
});
//if response is negative nothing is being done
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//creating and displaying the alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Source: Custom ListView Android Tutorial
Change the theme of the desired Activity. This works for me:
<activity
android:name="HomeActivity"
android:screenOrientation="landscape"
android:theme="@style/Theme.AppCompat.Light"
android:windowSoftInputMode="stateHidden" />
In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:
mtcars[, -which(names(mtcars) == "carb")] #only works on a single column
mtcars[, names(mtcars) != "carb"] #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")]
mtcars[, -match(c("carb", "mpg"), names(mtcars))]
mtcars2 <- mtcars; mtcars2$hp <- NULL #lost column (risky)
library(gdata)
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE)
Generally I use:
mtcars[, !names(mtcars) %in% c("carb", "mpg")]
because I feel it's safe and efficient.
To Expand on what @PythonIsGreat said, I create a global function that will do it for me:
var css = function(){
var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
return $.extend.apply(null, args);
}
This deeply extends the objects into a new object and allows for a variable number of objects as parameters. This allows you to do something like this:
return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);
var styles = {
base:{
//whatever
},
first:{
//whatever
},
second:{
//whatever
}
}
If you get an exception for : Invalid column type
Please use getNamedParameterJdbcTemplate()
instead of getJdbcTemplate()
List<Foo> foo = getNamedParameterJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",parameters,
getRowMapper());
Note that the second two arguments are swapped around.
I found an app for Mac OSX called ICOBundle that allows you to easily drop a selection of ico files in different sizes onto the ICOBundle.app, prompts you for a folder destination and file name, and it creates the multi-icon .ico file.
Now if it were only possible to mix-in an animated gif version into that one file it'd be a complete icon set, sadly not possible and requires a separate file and code snippet.
If your YAML file looks like this:
# tree format
treeroot:
branch1:
name: Node 1
branch1-1:
name: Node 1-1
branch2:
name: Node 2
branch2-1:
name: Node 2-1
And you've installed PyYAML
like this:
pip install PyYAML
And the Python code looks like this:
import yaml
with open('tree.yaml') as f:
# use safe_load instead load
dataMap = yaml.safe_load(f)
The variable dataMap
now contains a dictionary with the tree data. If you print dataMap
using PrettyPrint, you will get something like:
{
'treeroot': {
'branch1': {
'branch1-1': {
'name': 'Node 1-1'
},
'name': 'Node 1'
},
'branch2': {
'branch2-1': {
'name': 'Node 2-1'
},
'name': 'Node 2'
}
}
}
So, now we have seen how to get data into our Python program. Saving data is just as easy:
with open('newtree.yaml', "w") as f:
yaml.dump(dataMap, f)
You have a dictionary, and now you have to convert it to a Python object:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
Then you can use:
>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...
and follow "Convert Python dict to object".
For more information you can look at pyyaml.org and this.
Byte[] -> String: use system.convert.tobase64string
Convert.ToBase64String(byte[] data)
String -> Byte[]: use system.convert.frombase64string
Convert.FromBase64String(string data)
sql = "insert into Main (Firt Name, Last Name) values(textbox2.Text,textbox3.Text)";
(Firt Name) is not a valid field. It should be FirstName or First_Name. It may be your problem.
ffmpeg provides this functionality. All you need to do is run someting like
ffmpeg -i <inputfilename> -s 640x480 -b 512k -vcodec mpeg1video -acodec copy <outputfilename>
For newer versions of ffmpeg you need to change -b
to -b:v
:
ffmpeg -i <inputfilename> -s 640x480 -b:v 512k -vcodec mpeg1video -acodec copy <outputfilename>
to convert the input video file to a video with a size of 640 x 480 and a bitrate of 512 kilobits/sec using the MPEG 1 video codec and just copying the original audio stream. Of course, you can plug in any values you need and play around with the size and bitrate to achieve the quality/size tradeoff you are looking for. There are also a ton of other options described in the documentation
Run ffmpeg -formats
or ffmpeg -codecs
for a list of all of the available formats and codecs. If you don't have to target a specific codec for the final output, you can achieve better compression ratios with minimal quality loss using a state of the art codec like H.264.
Edit:
The problem i face is that HTML5 is all on one index page. So i need the timer to start on click of the blog link.
Try calling the setTimeout inside a click handler on the blog link,
$('#blogLink').click (function (e) {
e.preventDefault(); //will stop the link href to call the blog page
setTimeout(function () {
window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
}, 2000); //will call the function after 2 secs.
});
Try using setTimeout
function like below,
setTimeout(function () {
window.location.href = "blog.html"; //will redirect to your blog page (an ex: blog.html)
}, 2000); //will call the function after 2 secs.
Your code should work just as you expect it to if you add @classmethod
decorators.
@classmethod
def setup_class(cls):
"Runs once per class"
@classmethod
def teardown_class(cls):
"Runs at end of class"
See http://pythontesting.net/framework/pytest/pytest-xunit-style-fixtures/
Controller (Example: User.php)
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Users extends CI_controller
{
// Table
protected $table = 'users';
function index()
{
$data['users'] = $this->model->ra_object($this->table);
$this->load->view('users_list', $data);
}
}
View (Example: users_list.php)
<table>
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user) : ?>
<tr>
<td><?php echo $user->name; ?></td>
<td><?php echo $user->surname; ?></th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<!-- // User table -->
Something that just came out about a month ago is "Create React Native App," an awesome boilerplate that allows you (with minimal effort) to show what your app looks like live on your mobile device (ANY with a camera) using the Expo app. It not only has live updates, but it will allow you to see the console logs in your terminal just like when developing for the web, rather than having to use the browser like we did with React Native before.
You would, of course, have to make a new project with that boilerplate... but if you need to migrate your files over, that shouldn't be a problem. Give it a shot.
Edit: Actually it doesn't even require a camera. I said that for scanning a QR code, but you can also type out something to sync it up with your server, not just a QR code.
Works that way as well, a bit more tidy.
getQuery()
just returns the underlying builder, which already contains the table reference.
$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
->select('browser', $browser_total_raw)
->groupBy('browser')
->pluck('total','browser');
This approach is without using
max()
function
a = [1,2,3,4,6,7,99,88,999]
max_num = 0
for i in a:
if i > max_num:
max_num = i
print(max_num)
Also if you want to find the index of the resulting max,
print(a.index(max_num))
Direct approach by using function max()
max() function returns the item with the highest value, or the item with the highest value in an iterable
Example: when you have to find max on integers/numbers
a = (1, 5, 3, 9)
print(max(a))
>> 9
Example: when you have string
x = max("Mike", "John", "Vicky")
print(x)
>> Vicky
It basically returns the name with the highest value, ordered alphabetically.
I use this function (SQL Server 2005 and above).
create function [dbo].[Split]
(
@string nvarchar(4000),
@delimiter nvarchar(10)
)
returns @table table
(
[Value] nvarchar(4000)
)
begin
declare @nextString nvarchar(4000)
declare @pos int, @nextPos int
set @nextString = ''
set @string = @string + @delimiter
set @pos = charindex(@delimiter, @string)
set @nextPos = 1
while (@pos <> 0)
begin
set @nextString = substring(@string, 1, @pos - 1)
insert into @table
(
[Value]
)
values
(
@nextString
)
set @string = substring(@string, @pos + len(@delimiter), len(@string))
set @nextPos = @pos
set @pos = charindex(@delimiter, @string)
end
return
end
I used this function to download pdf stream from server.
function printPdf(url) {
var iframe = document.createElement('iframe');
// iframe.id = 'pdfIframe'
iframe.className='pdfIframe'
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.onload = function () {
setTimeout(function () {
iframe.focus();
iframe.contentWindow.print();
URL.revokeObjectURL(url)
// document.body.removeChild(iframe)
}, 1);
};
iframe.src = url;
// URL.revokeObjectURL(url)
}
Try either
sudo apt-get install php-zip
orsudo apt-get install php5.6-zip
Then, you might have to restart your web server.
sudo service apache2 restart
orsudo service nginx restart
If you are installing on centos or fedora OS then use yum in place of apt-get. example:-
sudo yum install php-zip
or
sudo yum install php5.6-zip
and
sudo service httpd restart
The difference between <pluginManagement/>
and <plugins/>
is that a <plugin/>
under:
<pluginManagement/>
defines the settings for plugins that will be inherited by modules in your build. This is great for cases where you have a parent pom file.
<plugins/>
is a section for the actual invocation of the plugins. It may or may not be inherited from a <pluginManagement/>
.
You don't need to have a <pluginManagement/>
in your project, if it's not a parent POM. However, if it's a parent pom, then in the child's pom, you need to have a declaration like:
<plugins>
<plugin>
<groupId>com.foo</groupId>
<artifactId>bar-plugin</artifactId>
</plugin>
</plugins>
Notice how you aren't defining any configuration. You can inherit it from the parent, unless you need to further adjust your invocation as per the child project's needs.
For more specific information, you can check:
The Maven pom.xml reference: Plugins
The Maven pom.xml reference: Plugin Management
In git version 2.14.3,
You can remove upstream using
git branch --unset-upstream
The above command will also remove the tracking stream branch, hence if you want to rebase from repository you have use
git rebase origin master
instead of git pull --rebase
We tried to implement RenderScript blur like mentioned above in different answers. We were limited to use the v8 RenderScript version and that caused us a lot of trouble.
I want to share our dirty Java-only version which is slow and should be done on a separate thread and, if possible, before usage and therefore persisted.
private final Paint mPaint = new Paint();
public Bitmap blur(final String pathToBitmap) {
final BitmapFactory.Options options = new BitmapFactory.Options();
final Bitmap normalOne = BitmapFactory.decodeFile(pathToBitmap, options);
final Bitmap resultBitmap = Bitmap.createBitmap(options.outWidth, options.outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(resultBitmap);
mPaint.setAlpha(180);
canvas.drawBitmap(normalOne, 0, 0, mPaint);
int blurRadius = 12;
for (int row = -blurRadius; row < blurRadius; row += 2) {
for (int col = -blurRadius; col < blurRadius; col += 2) {
if (col * col + row * row <= blurRadius * blurRadius) {
mPaint.setAlpha((blurRadius * blurRadius) / ((col * col + row * row) + 1) * 2);
canvas.drawBitmap(normalOne, row, col, mPaint);
}
}
}
normalOne.recycle();
return resultBitmap;
}
This solution is far from perfect but creates a reasonable blur effect based on the fact, that it draws highly transparent version of the same image on top of a barely transparent "sharp" version. The alpha depends on the distance to the origin.
You can adjust some "magic numbers" to your needs. I just wanted to share that "solution" for everybody who has issues with the v8 support version of RenderScript.
Check the length of the list given by of split() method.
if len(your_string.split()==0:
print("yes")
Or Compare output of strip() method with null.
if your_string.strip() == '':
print("yes")
//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
//Milliseconds to date
extension Int {
func dateFromMilliseconds() -> Date {
return Date(timeIntervalSince1970: TimeInterval(self)/1000)
}
}
I removed seemingly useless conversion via string and all those random !
.
Removing the Tomcat Server and adding new tomcat configuration in Eclipse resolved issue for me.
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
First check if your default_character_set_name is utf8.
SELECT default_character_set_name FROM information_schema.SCHEMATA S WHERE schema_name = "DBNAME";
If the result is not utf8 you must convert your database. At first you must save a dump.
To change the character set encoding to UTF-8 for all of the tables in the specified database, type the following command at the command line. Replace DBNAME with the database name:
mysql --database=DBNAME -B -N -e "SHOW TABLES" | awk '{print "SET foreign_key_checks = 0; ALTER TABLE", $1, "CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; SET foreign_key_checks = 1; "}' | mysql --database=DBNAME
To change the character set encoding to UTF-8 for the database itself, type the following command at the mysql> prompt. Replace DBNAME with the database name:
ALTER DATABASE DBNAME CHARACTER SET utf8 COLLATE utf8_general_ci;
You can now retry to to write utf8 character into your database. This solution help me when i try to upload 200000 row of csv file into my database.
Another tricky way that just occurred to me (tested and it worked!).
Conditional Formatting
, Highlight Cells
, Duplicate Values
Data
and then Filter
Filter based on color:
Admittedly, this is more for one-off checks of data than a spreadsheet you'll use often, since it requires some formatting changes.
Spring boot doc 'was' wrong (they have since fixed it) :
To switch it off you can set error.whitelabel.enabled=false
should be
To switch it off you can set server.error.whitelabel.enabled=false
I know this is quite an old question which already has a lot of answers, yet I still spent hours trying to actually do what I wanted:
Using Chrome headless (version 74.0.3729.157 as of this response), it is actually easy:
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --headless --screenshot --window-size=256,256 --default-background-color=0 button.html
Explanation of the command:
--headless
runs Chrome without opening it and exits after the command completes--screenshot
will capture a screenshot (note that it generates a file called screenshot.png
in the folder where the command is run)--window-size
allow to only capture a portion of the screen (format is --window-size=width,height
)--default-background-color=0
is the magic trick that tells Chrome to use a transparent background, not the default white colorIt's crude, but:
set pagesize 0 linesize 500 trimspool on feedback off echo off
select '"' || empno || '","' || ename || '","' || deptno || '"' as text
from emp
spool emp.csv
/
spool off
When a float
is passed to printf
, it is automatically converted to a double
. This is part of the default argument promotions, which apply to functions that have a variable parameter list (containing ...
), largely for historical reasons. Therefore, the “natural” specifier for a float
, %f
, must work with a double
argument. So the %f
and %lf
specifiers for printf
are the same; they both take a double
value.
When scanf
is called, pointers are passed, not direct values. A pointer to float
is not converted to a pointer to double
(this could not work since the pointed-to object cannot change when you change the pointer type). So, for scanf
, the argument for %f
must be a pointer to float
, and the argument for %lf
must be a pointer to double
.
if you want to access a method :
1) while using an object of a class:
Myclass myclass;
myclass.DoSomething();
2) while using a pointer to an object of a class:
Myclass *myclass=&abc;
myclass->DoSomething();
I took a bit of time to work out what is the best way of doing this. I also wanted to keep the state, when the user leaves the page and then presses the back button, to get back to the old page; and not just put all my data into the rootscope.
The final result is to have a service for each controller. In the controller, you just have functions and variables that you dont care about, if they are cleared.
The service for the controller is injected by dependency injection. As services are singletons, their data is not destroyed like the data in the controller.
In the service, I have a model. the model ONLY has data - no functions -. That way it can be converted back and forth from JSON to persist it. I used the html5 localstorage for persistence.
Lastly i used window.onbeforeunload
and $rootScope.$broadcast('saveState');
to let all the services know that they should save their state, and $rootScope.$broadcast('restoreState')
to let them know to restore their state ( used for when the user leaves the page and presses the back button to return to the page respectively).
Example service called userService for my userController :
app.factory('userService', ['$rootScope', function ($rootScope) {
var service = {
model: {
name: '',
email: ''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
}]);
userController example
function userCtrl($scope, userService) {
$scope.user = userService;
}
The view then uses binding like this
<h1>{{user.model.name}}</h1>
And in the app module, within the run function i handle the broadcasting of the saveState and restoreState
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
As i mentioned this took a while to come to this point. It is a very clean way of doing it, but it is a fair bit of engineering to do something that i would suspect is a very common issue when developing in Angular.
I would love to see easier, but as clean ways to handle keeping state across controllers, including when the user leaves and returns to the page.
To my experience on most SQL Servers there is no backup of the transaction log. Full backups or differential backups are common practice, but transaction log backups are really seldom. So the transaction log file grows forever (until the disk is full). In this case the recovery model should be set to "simple". Don't forget to modify the system databases "model" and "tempdb", too.
A backup of the database "tempdb" makes no sense, so the recovery model of this db should always be "simple".
From manual: s[i:j:k] slice of s from i to j with step k
li = range(100)
sub = li[0::10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio
are imho quite complicated when it comes to short and simple "hello world" example.
To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm
Add following includes to both files:
#include <cstdlib>
#include <cstring>
#include <unistd.h>
In client.c, change the line:
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
to:
if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
{ ... }
As you can see in C++ an explicit cast is needed.
I know this is a very old question but it may be that you need to set the request headers. This solved it for me.
For example 'user-agent', 'accept' etc. here is an example with user-agent:
url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)
According to the git-stash manpage, "A stash is represented as a commit whose tree records the state of the working directory, and its first parent is the commit at HEAD
when the stash was created," and git stash show -p
gives us "the changes recorded in the stash as a diff between the stashed state and its original parent.
To keep your other changes intact, use git stash show -p | patch --reverse
as in the following:
$ git init
Initialized empty Git repository in /tmp/repo/.git/
$ echo Hello, world >messages
$ git add messages
$ git commit -am 'Initial commit'
[master (root-commit)]: created 1ff2478: "Initial commit"
1 files changed, 1 insertions(+), 0 deletions(-)
create mode 100644 messages
$ echo Hello again >>messages
$ git stash
$ git status
# On branch master
nothing to commit (working directory clean)
$ git stash apply
# On branch master
# Changed but not updated:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: messages
#
no changes added to commit (use "git add" and/or "git commit -a")
$ echo Howdy all >>messages
$ git diff
diff --git a/messages b/messages
index a5c1966..eade523 100644
--- a/messages
+++ b/messages
@@ -1 +1,3 @@
Hello, world
+Hello again
+Howdy all
$ git stash show -p | patch --reverse
patching file messages
Hunk #1 succeeded at 1 with fuzz 1.
$ git diff
diff --git a/messages b/messages
index a5c1966..364fc91 100644
--- a/messages
+++ b/messages
@@ -1 +1,2 @@
Hello, world
+Howdy all
Edit:
A light improvement to this is to use git apply
in place of patch:
git stash show -p | git apply --reverse
Alternatively, you can also use git apply -R
as a shorthand to git apply --reverse
.
I've been finding this really handy lately...
This is what I am using,
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr="+latitude_cur+","+longitude_cur+"&daddr="+latitude+","+longitude));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_LAUNCHER );
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
You should use $.map
for this:
var array = ["one", "two", "three"];
var el = $.map(array, function(val, i) {
return "<span>" + val + "</span>";
});
$(".element").html(el.join(""));
You can pass array of variables to the compact as an arguement eg:
return view('yourView', compact(['var1','var2',....'varN']));
in view: if var1 is an object you can use it something like this
@foreach($var1 as $singleVar1)
{{$singleVar1->property}}
@endforeach
incase of single variable you can simply
{{$var2}}
i have done this several times without any issues
We are able to swap var like this :
var val1 = 117,
val2 = 327;
val2 = val1-val2;
console.log(val2);
val1 = val1-val2;
console.log(val1);
val2 = val1+val2;
console.log(val2);
You should try doing it with css3 animation. Check the code bellow:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: relative;
-webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
-webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
animation: myfirst 5s infinite;
animation-direction: alternate;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
@keyframes myfirst {
0% {background: red; left: 0px; top: 0px;}
25% {background: yellow; left: 200px; top: 0px;}
50% {background: blue; left: 200px; top: 200px;}
75% {background: green; left: 0px; top: 200px;}
100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>
<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>
</body>
</html>
Where 'div' is your animated object.
I hope you find this useful.
Thanks.
Although I'm not answering the original question concering the no-op command, many (if not most) problems when one may think "in this branch I have to do nothing" can be bypassed by simply restructuring the logic so that this branch won't occur.
I try to give a general rule by using the OPs example
do nothing when $a is greater than "10", print "1" if $a is less than "5", otherwise, print "2"
we have to avoid a branch where $a
gets more than 10, so $a < 10
as a general condition can be applied to every other, following condition.
In general terms, when you say do nothing when X, then rephrase it as avoid a branch where X. Usually you can make the avoidance happen by simply negating X and applying it to all other conditions.
So the OPs example with the rule applied may be restructured as:
if [ "$a" -lt 10 ] && [ "$a" -le 5 ]
then
echo "1"
elif [ "$a" -lt 10 ]
then
echo "2"
fi
Just a variation of the above, enclosing everything in the $a < 10
condition:
if [ "$a" -lt 10 ]
then
if [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
fi
(For this specific example @Flimzys restructuring is certainly better, but I wanted to give a general rule for all the people searching how to do nothing.)
Is this what you are after? Just index the element and assign a new value.
A[2,1]=150
A
Out[345]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 150, 11, 12],
[13, 14, 15, 16]])
Looks to me like to would be something like
library(tutoR)
format(1.128347132904321674821, 2)
Per a little online help.
in my jenkins/jenkins docker sudo always generates error:
bash: sudo: command not found
I needed update repo list with:
curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
then,
apt-get install nodejs
All the command line results like this:
root@76e6f92724d1:/# curl -sL https://deb.nodesource.com/setup_10.x | apt-get update
Ign:1 http://deb.debian.org/debian stretch InRelease
Get:2 http://security.debian.org/debian-security stretch/updates InRelease [94.3 kB]
Get:3 http://deb.debian.org/debian stretch-updates InRelease [91.0 kB]
Get:4 http://deb.debian.org/debian stretch Release [118 kB]
Get:5 http://security.debian.org/debian-security stretch/updates/main amd64 Packages [520 kB]
Get:6 http://deb.debian.org/debian stretch-updates/main amd64 Packages [27.9 kB]
Get:8 http://deb.debian.org/debian stretch Release.gpg [2410 B]
Get:9 http://deb.debian.org/debian stretch/main amd64 Packages [7083 kB]
Get:7 https://packagecloud.io/github/git-lfs/debian stretch InRelease [23.2 kB]
Get:10 https://packagecloud.io/github/git-lfs/debian stretch/main amd64 Packages [4675 B]
Fetched 7965 kB in 20s (393 kB/s)
Reading package lists... Done
root@76e6f92724d1:/# apt-get install nodejs
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
libicu57 libuv1
The following NEW packages will be installed:
libicu57 libuv1 nodejs
0 upgraded, 3 newly installed, 0 to remove and 0 not upgraded.
Need to get 11.2 MB of archives.
After this operation, 45.2 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://deb.debian.org/debian stretch/main amd64 libicu57 amd64 57.1-6+deb9u3 [7705 kB]
Get:2 http://deb.debian.org/debian stretch/main amd64 libuv1 amd64 1.9.1-3 [84.4 kB]
Get:3 http://deb.debian.org/debian stretch/main amd64 nodejs amd64 4.8.2~dfsg-1 [3440 kB]
Fetched 11.2 MB in 26s (418 kB/s)
debconf: delaying package configuration, since apt-utils is not installed
Selecting previously unselected package libicu57:amd64.
(Reading database ... 12488 files and directories currently installed.)
Preparing to unpack .../libicu57_57.1-6+deb9u3_amd64.deb ...
Unpacking libicu57:amd64 (57.1-6+deb9u3) ...
Selecting previously unselected package libuv1:amd64.
Preparing to unpack .../libuv1_1.9.1-3_amd64.deb ...
Unpacking libuv1:amd64 (1.9.1-3) ...
Selecting previously unselected package nodejs.
Preparing to unpack .../nodejs_4.8.2~dfsg-1_amd64.deb ...
Unpacking nodejs (4.8.2~dfsg-1) ...
Setting up libuv1:amd64 (1.9.1-3) ...
Setting up libicu57:amd64 (57.1-6+deb9u3) ...
Processing triggers for libc-bin (2.24-11+deb9u4) ...
Setting up nodejs (4.8.2~dfsg-1) ...
update-alternatives: using /usr/bin/nodejs to provide /usr/bin/js (js) in auto mode
Below is the work around to submit Multi values, in case of converting the application from ASP to PHP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<script language="javascript">
function SetValuesOfSameElements() {
var Arr_Elements = [];
Arr_Elements = document.getElementsByClassName("MultiElements");
for(var i=0; i<Arr_Elements.length; i++) {
Arr_Elements[i].value = '';
var Element_Name = Arr_Elements[i].name;
var Main_Element_Type = Arr_Elements[i].getAttribute("MainElementType");
var Multi_Elements = [];
Multi_Elements = document.getElementsByName(Element_Name);
var Multi_Elements_Values = '';
//alert(Element_Name + " > " + Main_Element_Type + " > " + Multi_Elements_Values);
if (Main_Element_Type == "CheckBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements[j].checked == true) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
if (Main_Element_Type == "Hidden" || Main_Element_Type == "TextBox") {
for(var j=0; j<Multi_Elements.length; j++) {
if (Multi_Elements_Values == '') {
Multi_Elements_Values = Multi_Elements[j].value;
}
else {
if (Multi_Elements[j].value != '') {
Multi_Elements_Values += ', '+ Multi_Elements[j].value;
}
}
}
}
Arr_Elements[i].value = Multi_Elements_Values;
}
}
</script>
<BODY>
<form name="Training" action="TestCB.php" method="get" onsubmit="SetValuesOfSameElements()"/>
<table>
<tr>
<td>Check Box</td>
<td>
<input type="CheckBox" name="TestCB" id="TestCB" value="123">123</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="234">234</input>
<input type="CheckBox" name="TestCB" id="TestCB" value="345">345</input>
</td>
<td>
<input type="hidden" name="SdPart" id="SdPart" value="1231"></input>
<input type="hidden" name="SdPart" id="SdPart" value="2341"></input>
<input type="hidden" name="SdPart" id="SdPart" value="3451"></input>
<input type="textbox" name="Test11" id="Test11" value="345111"></input>
<!-- Define hidden Elements with Class name 'MultiElements' for all the Form Elements that used the Same Name (Check Boxes, Multi Select, Text Elements with the Same Name, Hidden Elements with the Same Name, etc
-->
<input type="hidden" MainElementType="CheckBox" name="TestCB" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="Hidden" name="SdPart" class="MultiElements" value=""></input>
<input type="hidden" MainElementType="TextBox" name="Test11" class="MultiElements" value=""></input>
</td>
</tr>
<tr>
<td colspan="2">
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</td>
</tr>
</table>
</form>
</BODY>
</HTML>
testCB.php
<?php
echo $_GET["TestCB"];
echo "<br/>";
echo $_GET["SdPart"];
echo "<br/>";
echo $_GET["Test11"];
?>
The differences between Model()
and Model.objects.create()
are the following:
INSERT vs UPDATE
Model.save()
does either INSERT or UPDATE of an object in a DB, while Model.objects.create()
does only INSERT.
Model.save()
does
UPDATE If the object’s primary key attribute is set to a value that evaluates to True
INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).
Existing primary key
If primary key attribute is set to a value and such primary key already exists, then Model.save()
performs UPDATE, but Model.objects.create()
raises IntegrityError
.
Consider the following models.py:
class Subject(models.Model):
subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
name = models.CharField(max_length=255)
max_marks = models.PositiveIntegerField()
Insert/Update to db with Model.save()
physics = Subject(subject_id=1, name='Physics', max_marks=100)
physics.save()
math = Subject(subject_id=1, name='Math', max_marks=50) # Case of update
math.save()
Result:
Subject.objects.all().values()
<QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
Insert to db with Model.objects.create()
Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
IntegrityError: UNIQUE constraint failed: m****t.subject_id
Explanation: In the example, math.save()
does an UPDATE (changes name
from Physics to Math, and max_marks
from 100 to 50), because subject_id
is a primary key and subject_id=1
already exists in the DB. But Subject.objects.create()
raises IntegrityError
, because, again the primary key subject_id
with the value 1
already exists.
Forced insert
Model.save()
can be made to behave as Model.objects.create()
by using force_insert=True
parameter: Model.save(force_insert=True)
.
Return value
Model.save()
return None
where Model.objects.create()
return model instance i.e. package_name.models.Model
Conclusion: Model.objects.create()
does model initialization and performs save()
with force_insert=True
.
Excerpt from the source code of Model.objects.create()
def create(self, **kwargs):
"""
Create a new object with the given kwargs, saving it to the database
and returning the created object.
"""
obj = self.model(**kwargs)
self._for_write = True
obj.save(force_insert=True, using=self.db)
return obj
For more details follow the links:
What does the exclamation mark after the gem name in the 'DEPENDECIES' group mean?
The exclamation mark appears when the gem was installed using a source other than "https://rubygems.org".
I got such a problem after I upgraded my node version with brew. To fix the problem
1)run $brew doctor
to check out if it is successfully installed or not
2) In case you missed clearing any node-related file before, such error log might pop up:
Warning: You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built.
node
3) Now you are recommended to run brew link command to delete the original node-related files and overwrite new files - $ brew link node
.
And that's it - everything works again !!!
It is very simple using Sass, just use @extend
:
.pull-right-xs {
@extend .pull-right;
}
Yet another method, using StringTokenizer :
String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);
while(tokenizer.hasMoreTokens()) {
System.out.println(tokenizer.nextToken());
}
I would like to add an answer to enjoy the beauty of C ++ language. Its adaptability to work at high and low levels. Happy programming.
public:template <class T,class U> U* Int2Hex(T lnumber, U* buffer)
{
const char* ref = "0123456789ABCDEF";
T hNibbles = (lnumber >> 4);
unsigned char* b_lNibbles = (unsigned char*)&lnumber;
unsigned char* b_hNibbles = (unsigned char*)&hNibbles;
U* pointer = buffer + (sizeof(lnumber) << 1);
*pointer = 0;
do {
*--pointer = ref[(*b_lNibbles++) & 0xF];
*--pointer = ref[(*b_hNibbles++) & 0xF];
} while (pointer > buffer);
return buffer;
}
Examples:
char buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns "0000000012345678"
Int2Hex(305419896UL, buffer);//returns "12345678"
Int2Hex((short)65533, buffer);//returns "FFFD"
Int2Hex((char)18, buffer);//returns "12"
wchar_t buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns L"0000000012345678"
Int2Hex(305419896UL, buffer);//returns L"12345678"
Int2Hex((short)65533, buffer);//returns L"FFFD"
Int2Hex((char)18, buffer);//returns L"12"
GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.
Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).
I am wondering if you are after something like Squiggle. Also something very useful is jDBI. It won't help you with the queries though.
Like Jonathan suggested, using textView.setTextTypeface
works, I just used it in an app a few seconds ago.
textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.
Adding this late answer to show a case most people will come across. If you only need to see what is the last item in the list, use the last
key word:
<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last">
<divider *ngIf="!last"></divider>
</div>
This will add the divider component to every item except the last.
Because of the comment below, I will add the rest of the ngFor
exported values that can be aliased to local variables (As are shown in the docs):
There is a lot more to coalesce than just a replacement for ISNULL. I completely agree that the official "documentation" of coalesce is vague and unhelpful. This article helps a lot. http://www.mssqltips.com/sqlservertip/1521/the-many-uses-of-coalesce-in-sql-server/
You might want to try this: http://jsfiddle.net/QPKVX/
Not really sure what you want your final layout to look like- but that fixes the colspan problem too.
While creating OkHttpClient
that will be used for Retrofit.
add an Interceptor like this.
private val httpClient = OkHttpClient.Builder()
.addInterceptor (other interceptors)
........................................
//This Interceptor is the main logging Interceptor
.addInterceptor { chain ->
val request = chain.request()
val jsonObj = JSONObject(Gson().toJson(request))
val requestBody = (jsonObj
?.getJSONObject("tags")
?.getJSONObject("class retrofit2.Invocation")
?.getJSONArray("arguments")?.get(0) ?: "").toString()
val url = jsonObj?.getJSONObject("url")?.getString("url") ?: ""
Timber.d("gsonrequest request url: $url")
Timber.d("gsonrequest body :$requestBody")
chain.proceed(request)
}
..............
// Add other configurations
.build()
Now your every Retrofit call's URL and request body will be logged in Logcat
. Filter it by "gsonrequest"
How to convert decimal to hexadecimal in JavaScript
I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.
function DecToHex(decimal) { // Data (decimal)
length = -1; // Base string length
string = ''; // Source 'string'
characters = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' ]; // character array
do { // Grab each nibble in reverse order because JavaScript has no unsigned left shift
string += characters[decimal & 0xF]; // Mask byte, get that character
++length; // Increment to length of string
} while (decimal >>>= 4); // For next character shift right 4 bits, or break on 0
decimal += 'x'; // Convert that 0 into a hex prefix string -> '0x'
do
decimal += string[length];
while (length--); // Flip string forwards, with the prefixed '0x'
return (decimal); // return (hexadecimal);
}
/* Original: */
D = 3678; // Data (decimal)
C = 0xF; // Check
A = D; // Accumulate
B = -1; // Base string length
S = ''; // Source 'string'
H = '0x'; // Destination 'string'
do {
++B;
A& = C;
switch(A) {
case 0xA: A='A'
break;
case 0xB: A='B'
break;
case 0xC: A='C'
break;
case 0xD: A='D'
break;
case 0xE: A='E'
break;
case 0xF: A='F'
break;
A = (A);
}
S += A;
D >>>= 0x04;
A = D;
} while(D)
do
H += S[B];
while (B--)
S = B = A = C = D; // Zero out variables
alert(H); // H: holds hexadecimal equivalent
The best solution is to use NestedScrollVew with RecyclerView or if you want to go with Listview then you can add header and footer view to this. For example:
View footerView = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.outofoffice_footer_view, null, false);
infoListView.addFooterView(footerView);
Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.
The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.
Here is a good article about fluid vs. flex.
Just run this inside the directory where you installed your project
composer install
Was having the same error and fixing the credentials in the IIS app pool did not help. I finally resolved the error in IIS by selecting my website under Default Web Site, Advanced Settings->Physical Path Credentials->Specific User, and reentered the credentials for the app pool user, then restarted IIS and the error went away and my website came up successfully.
try
define("DB_PASSWORD", null);
and those are warnings try
$db = @mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
But i will recommend you to set a root password
Dear olga is clear what the message says. Turn off the custom errors to see the details about this error for fix it, and then you close them back. So add mode="off" as:
<configuration>
<system.web>
<customErrors mode="Off"/>
</system.web>
</configuration>
Relative answer: Deploying website: 500 - Internal server error
By the way: The error message declare that the web.config is not the one you type it here. Maybe you have forget to upload your web.config ? And remember to close the debug flag on the web.config that you use for online pages.
Adding the following two lines in the script solved the issue for me.
# !/usr/bin/python
# coding=utf-8
Hope it helps !
I got the same error in ReactJS function component, using ReactJS useState hook. The solution was to declare the type of useState at initialisation:
const [items , setItems] = useState<IItem[]>([]); // replace IItem[] with your own typing: string, boolean...
Quick fix that worked for me:
for file in $(find "$JAVA_HOME" -name "*pack")
do
unpack200 "${file}" "${test_file/%pack/jar}";
done
It is best practice to always supply the permission when registering the receiver, otherwise you will receive for any application that sends a matching intent. This can allow malicious apps to broadcast to your receiver.
If not all of your document scrolls, say, when you have a scrolling div
within the document, then the above solutions won't work without adaptations. Here's how to check whether the div's scrollbar has hit the bottom:
$('#someScrollingDiv').on('scroll', function() {
let div = $(this).get(0);
if(div.scrollTop + div.clientHeight >= div.scrollHeight) {
// do the lazy loading here
}
});
You don't even need an MTA. The SMTP protocol is simple enough to directly write it to your SMTP server. You can even communicate over SSL/TLS if you have the OpenSSL package installed. Check this post: https://33hops.com/send-email-from-bash-shell.html
The above is an example on how to send text/html e-mails that will work out of the box. If you want to add attachments the thing can get a bit more complicated, you will need to base64 encode the binary files and embed them between boundaries. THis is a good place to start investigating: http://forums.codeguru.com/showthread.php?418377-Send-Email-w-attachments-using-SMTP
For new browsers: Object.keys( MY_DICTIONARY )
will return an array of keys. Else you may want to go the old school way:
var keys = []
for(var key in dic) keys.push( key );
Check this fiddle.
$('#email').bind("cut copy paste",function(e) {
e.preventDefault();
});
You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.
You can find a detailed explanation here.
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
@Html.TextArea("txtNotes", "", 4, 0, new { @class = "k-textbox", style = "width: 100%; height: 100%;" })
Came here with a similar question, the above didn't work for me in: "rxjs": "^6.0.0"
, in order to generate an observable that emits no data I needed to do:
import {Observable,empty} from 'rxjs';
class ActivatedRouteStub {
params: Observable<any> = empty();
}
It isn't that hard to deal with the character array itself without converting the array to a string. Especially in the case where the length of the character array is know or can be easily found. With the character array, the length must be determined in the same scope as the array definition, e.g.:
size_t len sizeof myarray/sizeof *myarray;
For strings you, of course, have strlen
available.
With the length known, regardless of whether it is a character array or a string, you can convert the character values to a number with a short function similar to the following:
/* convert character array to integer */
int char2int (char *array, size_t n)
{
int number = 0;
int mult = 1;
n = (int)n < 0 ? -n : n; /* quick absolute value check */
/* for each character in array */
while (n--)
{
/* if not digit or '-', check if number > 0, break or continue */
if ((array[n] < '0' || array[n] > '9') && array[n] != '-') {
if (number)
break;
else
continue;
}
if (array[n] == '-') { /* if '-' if number, negate, break */
if (number) {
number = -number;
break;
}
}
else { /* convert digit to numeric value */
number += (array[n] - '0') * mult;
mult *= 10;
}
}
return number;
}
Above is simply the standard char to int conversion approach with a few additional conditionals included. To handle stray characters, in addition to the digits
and '-'
, the only trick is making smart choices about when to start collecting digits and when to stop.
If you start collecting digits
for conversion when you encounter the first digit
, then the conversion ends when you encounter the first '-'
or non-digit
. This makes the conversion much more convenient when interested in indexes such as (e.g. file_0127.txt
).
A short example of its use:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int char2int (char *array, size_t n);
int main (void) {
char myarray[4] = {'-','1','2','3'};
char *string = "some-goofy-string-with-123-inside";
char *fname = "file-0123.txt";
size_t mlen = sizeof myarray/sizeof *myarray;
size_t slen = strlen (string);
size_t flen = strlen (fname);
printf ("\n myarray[4] = {'-','1','2','3'};\n\n");
printf (" char2int (myarray, mlen): %d\n\n", char2int (myarray, mlen));
printf (" string = \"some-goofy-string-with-123-inside\";\n\n");
printf (" char2int (string, slen) : %d\n\n", char2int (string, slen));
printf (" fname = \"file-0123.txt\";\n\n");
printf (" char2int (fname, flen) : %d\n\n", char2int (fname, flen));
return 0;
}
Note: when faced with '-'
delimited file indexes (or the like), it is up to you to negate the result. (e.g. file-0123.txt
compared to file_0123.txt
where the first would return -123
while the second 123
).
Example Output
$ ./bin/atoic_array
myarray[4] = {'-','1','2','3'};
char2int (myarray, mlen): -123
string = "some-goofy-string-with-123-inside";
char2int (string, slen) : -123
fname = "file-0123.txt";
char2int (fname, flen) : -123
Note: there are always corner cases, etc. that can cause problems. This isn't intended to be 100% bulletproof in all character sets, etc., but instead work an overwhelming majority of the time and provide additional conversion flexibility without the initial parsing or conversion to string required by atoi
or strtol
, etc.
Another way to do it:
>>> set(['a','b']).issubset( ['b','a','foo','bar'] )
True
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
I'm arriving at this same issue - while I like the tee()
solution, I don't know how big my files are going to be and the memory warnings about consuming one first before the other are putting me off adopting that method.
Instead, I'm creating a pair of iterators using iter()
statements, and using the first for my initial run-through, before switching to the second one for the final run.
So, in the case of a dict-reader, if the reader is defined using:
d = csv.DictReader(f, delimiter=",")
I can create a pair of iterators from this "specification" - using:
d1, d2 = iter(d), iter(d)
I can then run my 1st-pass code against d1
, safe in the knowledge that the second iterator d2
has been defined from the same root specification.
I've not tested this exhaustively, but it appears to work with dummy data.
This will do it:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
There is a better why to determine type of an image. with exif_imagetype
If you use this function, you can tell image's real extension.
with this function filename's extension is completely irrelevant, which is good.
function setHeaderContentType(string $filePath): void
{
$numberToContentTypeMap = [
'1' => 'image/gif',
'2' => 'image/jpeg',
'3' => 'image/png',
'6' => 'image/bmp',
'17' => 'image/ico'
];
$contentType = $numberToContentTypeMap[exif_imagetype($filePath)] ?? null;
if ($contentType === null) {
throw new Exception('Unable to determine content type of file.');
}
header("Content-type: $contentType");
}
You can add more types from the link.
Hope it helps.
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.
LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.
Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.
As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.
Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.
If you are dealing with String[] instead of int[], We can use
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));
Use the (ngModelChange)
event to detect changes on the model
Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/
angular.module('App', [])
.controller('AppCtrl', function ($scope) {
$scope.model = 0;
$scope.initSlider = function () {
$(function () {
// wait till load event fires so all resources are available
$scope.$slider = $('#slider').slider({
slide: $scope.onSlide
});
});
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
$scope.$digest();
};
};
$scope.initSlider();
});
The directive approach:
HTML
<div slider></div>
JS
angular.module('App', [])
.directive('slider', function (DataModel) {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $element, $attrs) {
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
// or set it on the model
// DataModel.model = ui.value;
// add to angular digest cycle
$scope.$digest();
};
},
link: function (scope, el, attrs) {
var options = {
slide: scope.onSlide
};
// set up slider on load
angular.element(document).ready(function () {
scope.$slider = $(el).slider(options);
});
}
}
});
I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js
You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.
First create a baseViewController
and add viewDidLoad
this code "swift4":
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
}
// Example Tabbar 5 pages
@objc func swiped(_ gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
if (self.tabBarController?.selectedIndex)! < 5 {
self.tabBarController?.selectedIndex += 1
}
} else if gesture.direction == .right {
if (self.tabBarController?.selectedIndex)! > 0 {
self.tabBarController?.selectedIndex -= 1
}
}
}
}
And use this baseController
class:
class YourViewController: BaseViewController {
// its done. Swipe successful
//Now you can use all the Controller you have created without writing any code.
}
The null character '\0'
(also null terminator
), abbreviated NUL
, is a control character with the value zero
. Its the same in C and objective C
The character has much more significance in C and it serves as a reserved character used to signify the end of a string
,often called a null-terminated string
The length of a C string (an array containing the characters and terminated with a '\0'
character) is found by searching for the (first) NUL byte.
Static variable in a header file:
say 'common.h'
has
static int zzz;
This variable 'zzz'
has internal linkage (This same variable can not be accessed in other translation units). Each translation unit which includes 'common.h'
has it's own unique object of name 'zzz'
.
Static variable in a class:
Static variable in a class is not a part of the subobject of the class. There is only one copy of a static data member shared by all the objects of the class.
$9.4.2/6 - "Static data members of a class in namespace scope have external linkage (3.5).A local class shall not have static data members."
So let's say 'myclass.h'
has
struct myclass{
static int zzz; // this is only a declaration
};
and myclass.cpp
has
#include "myclass.h"
int myclass::zzz = 0 // this is a definition,
// should be done once and only once
and "hisclass.cpp"
has
#include "myclass.h"
void f(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
and "ourclass.cpp"
has
#include "myclass.h"
void g(){myclass::zzz = 2;} // myclass::zzz is always the same in any
// translation unit
So, class static members are not limited to only 2 translation units. They need to be defined only once in any one of the translation units.
Note: usage of 'static' to declare file scope variable is deprecated and unnamed namespace is a superior alternate
@Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit: If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this: (I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
overflow-y : scroll;
overflow-x : hidden;
height
is optional
My problem was not resolved with this procedure
FirebaseApp.initializeApp(this);
So I tried something else and now my firebase has been successfully initialized. Try adding following in app module.gradle
BuildScript{
dependencies {..
classpath : "com.google.firebase:firebase-plugins:1.1.5"
..}
}
dependencies {...
implementation : "com.google.firebase:firebase-perf:16.1.0"
implementation : "com.google.firebase:firebase-core:16.0.3"
..}
Bootstrap 2.3.2
<ul class="inline">
<li>...</li>
</ul>
Bootstrap 3
<ul class="list-inline">
<li>...</li>
</ul>
Bootstrap 4
<ul class="list-inline">
<li class="list-inline-item">Lorem ipsum</li>
<li class="list-inline-item">Phasellus iaculis</li>
<li class="list-inline-item">Nulla volutpat</li>
</ul>
source: http://v4-alpha.getbootstrap.com/content/typography/#inline
Updated link https://getbootstrap.com/docs/4.4/content/typography/#inline
As a Python programmer, Hungarian Notation falls apart pretty fast. In Python, I don't care if something is a string - I care if it can act like a string (i.e. if it has a ___str___()
method which returns a string).
For example, let's say we have foo as an integer, 12
foo = 12
Hungarian notation tells us that we should call that iFoo or something, to denote it's an integer, so that later on, we know what it is. Except in Python, that doesn't work, or rather, it doesn't make sense. In Python, I decide what type I want when I use it. Do I want a string? well if I do something like this:
print "The current value of foo is %s" % foo
Note the %s
- string. Foo isn't a string, but the %
operator will call foo.___str___()
and use the result (assuming it exists). foo
is still an integer, but we treat it as a string if we want a string. If we want a float, then we treat it as a float. In dynamically typed languages like Python, Hungarian Notation is pointless, because it doesn't matter what type something is until you use it, and if you need a specific type, then just make sure to cast it to that type (e.g. float(foo)
) when you use it.
Note that dynamic languages like PHP don't have this benefit - PHP tries to do 'the right thing' in the background based on an obscure set of rules that almost no one has memorized, which often results in catastrophic messes unexpectedly. In this case, some sort of naming mechanism, like $files_count
or $file_name
, can be handy.
In my view, Hungarian Notation is like leeches. Maybe in the past they were useful, or at least they seemed useful, but nowadays it's just a lot of extra typing for not a lot of benefit.
I agree with @Mahomedalid's answer, but I didn't want to do something like a prepared statement and I didn't want to type all the fields, so what I had was a silly solution.
Go to the table in phpmyadmin->sql->select, it dumps the query: copy, replace and done! :)
LOL, a super lame hack, but at least curl and firefox accepts it:
while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l 1500 ; done
You better replace it soon with something proper!
Ah yes, my nc
were not exactly the same as yours, it did not like the -p
option.
You're trying to access a string
as if it were an array, with a key that's a string
. string
will not understand that. In code we can see the problem:
"hello"["hello"];
// PHP Warning: Illegal string offset 'hello' in php shell code on line 1
"hello"[0];
// No errors.
array("hello" => "val")["hello"];
// No errors. This is *probably* what you wanted.
Warning: Illegal string offset 'port' in ...
What does it say? It says we're trying to use the string 'port'
as an offset for a string. Like this:
$a_string = "string";
// This is ok:
echo $a_string[0]; // s
echo $a_string[1]; // t
echo $a_string[2]; // r
// ...
// !! Not good:
echo $a_string['port'];
// !! Warning: Illegal string offset 'port' in ...
For some reason you expected an array
, but you have a string
. Just a mix-up. Maybe your variable was changed, maybe it never was an array
, it's really not important.
If we know we should have an array
, we should do some basic debugging to determine why we don't have an array
. If we don't know if we'll have an array
or string
, things become a bit trickier.
What we can do is all sorts of checking to ensure we don't have notices, warnings or errors with things like is_array
and isset
or array_key_exists
:
$a_string = "string";
$an_array = array('port' => 'the_port');
if (is_array($a_string) && isset($a_string['port'])) {
// No problem, we'll never get here.
echo $a_string['port'];
}
if (is_array($an_array) && isset($an_array['port'])) {
// Ok!
echo $an_array['port']; // the_port
}
if (is_array($an_array) && isset($an_array['unset_key'])) {
// No problem again, we won't enter.
echo $an_array['unset_key'];
}
// Similar, but with array_key_exists
if (is_array($an_array) && array_key_exists('port', $an_array)) {
// Ok!
echo $an_array['port']; // the_port
}
There are some subtle differences between isset
and array_key_exists
. For example, if the value of $array['key']
is null
, isset
returns false
. array_key_exists
will just check that, well, the key exists.
The pickle Python library implements binary protocols for serializing and de-serializing a Python object.
When you import torch
(or when you use PyTorch) it will import pickle
for you and you don't need to call pickle.dump()
and pickle.load()
directly, which are the methods to save and to load the object.
In fact, torch.save()
and torch.load()
will wrap pickle.dump()
and pickle.load()
for you.
A state_dict
the other answer mentioned deserves just few more notes.
What state_dict
do we have inside PyTorch?
There are actually two state_dict
s.
The PyTorch model is torch.nn.Module
has model.parameters()
call to get learnable parameters (w and b).
These learnable parameters, once randomly set, will update over time as we learn.
Learnable parameters are the first state_dict
.
The second state_dict
is the optimizer state dict. You recall that the optimizer is used to improve our learnable parameters. But the optimizer state_dict
is fixed. Nothing to learn in there.
Because state_dict
objects are Python dictionaries, they can be easily saved, updated, altered, and restored, adding a great deal of modularity to PyTorch models and optimizers.
Let's create a super simple model to explain this:
import torch
import torch.optim as optim
model = torch.nn.Linear(5, 2)
# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
print("Model's state_dict:")
for param_tensor in model.state_dict():
print(param_tensor, "\t", model.state_dict()[param_tensor].size())
print("Model weight:")
print(model.weight)
print("Model bias:")
print(model.bias)
print("---")
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
print(var_name, "\t", optimizer.state_dict()[var_name])
This code will output the following:
Model's state_dict:
weight torch.Size([2, 5])
bias torch.Size([2])
Model weight:
Parameter containing:
tensor([[ 0.1328, 0.1360, 0.1553, -0.1838, -0.0316],
[ 0.0479, 0.1760, 0.1712, 0.2244, 0.1408]], requires_grad=True)
Model bias:
Parameter containing:
tensor([ 0.4112, -0.0733], requires_grad=True)
---
Optimizer's state_dict:
state {}
param_groups [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [140695321443856, 140695321443928]}]
Note this is a minimal model. You may try to add stack of sequential
model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.Conv2d(A, B, C)
torch.nn.Linear(H, D_out),
)
Note that only layers with learnable parameters (convolutional layers, linear layers, etc.) and registered buffers (batchnorm layers) have entries in the model's state_dict
.
Non learnable things, belong to the optimizer object state_dict
, which contains information about the optimizer's state, as well as the hyperparameters used.
The rest of the story is the same; in the inference phase (this is a phase when we use the model after training) for predicting; we do predict based on the parameters we learned. So for the inference, we just need to save the parameters model.state_dict()
.
torch.save(model.state_dict(), filepath)
And to use later model.load_state_dict(torch.load(filepath)) model.eval()
Note: Don't forget the last line model.eval()
this is crucial after loading the model.
Also don't try to save torch.save(model.parameters(), filepath)
. The model.parameters()
is just the generator object.
On the other side, torch.save(model, filepath)
saves the model object itself, but keep in mind the model doesn't have the optimizer's state_dict
. Check the other excellent answer by @Jadiel de Armas to save the optimizer's state dict.
Since Java 8 you can use the argument-less any
method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
In this case the parameter type of doStuff
will be the target type for any()
, and the return value type of any()
will get chosen to match that argument type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
This doesn't work with primitive types, unfortunately:
public interface IBar {
void doPrimitiveStuff(int i);
}
verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
The problem is that the compiler will infer Integer
as the return value type of any()
. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null
. The runtime will try to unbox the return value by calling the intValue
method on it before passing it to doStuff
, and the exception gets thrown.
Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.
View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are
I use life hacking like this
@Configuration
@EnableCaching
@EnableScheduling
public class CachingConfig {
public static final String GAMES = "GAMES";
@Bean
public CacheManager cacheManager() {
ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager(GAMES);
return cacheManager;
}
@CacheEvict(allEntries = true, value = {GAMES})
@Scheduled(fixedDelay = 10 * 60 * 1000 , initialDelay = 500)
public void reportCacheEvict() {
System.out.println("Flush Cache " + dateFormat.format(new Date()));
}
Inf
is infinity, it's a "bigger than all the other numbers" number. Try subtracting anything you want from it, it doesn't get any smaller. All numbers are < Inf
. -Inf
is similar, but smaller than everything.
NaN
means not-a-number. If you try to do a computation that just doesn't make sense, you get NaN
. Inf - Inf
is one such computation. Usually NaN
is used to just mean that some data is missing.
If you use Intent.ACTION_CALL
you must add CALL_PHONE
permission.
Its okey only if you don't want your app to show up in google play for tablets that doesn't take SIM card or doesn't have GSM.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + Constants.CALL_CENTER_NUMBER));
startActivity(callIntent);
<uses-permission android:name="android.permission.CALL_PHONE" />
So if it is not critical feature to your app, try to stay away from adding CALL_PHONE
permission.
Is to show the Phone app with the number written in on the screen, so user will only need to click call button:
Intent dialIntent = new Intent(Intent.ACTION_DIAL);
dialIntent.setData(Uri.parse("tel:" + Constants.CALL_CENTER_NUMBER));
startActivity(dialIntent);
No permission needed for this.
EDIT: see bobince's solution which uses contains rather than start-with, along with a trick to ensure the comparison is done at the level of a complete token (lest the 'atag' pattern be found as part of another 'tag').
"atag btag" is an odd value for the class attribute, but never the less, try:
//*[starts-with(@class,"atag")]
https://docs.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql
image
Variable-length binary data from 0 through 2^31-1 (2,147,483,647) bytes. Still it IS supported to use image datatype, but be aware of:
https://docs.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql
varbinary [ ( n | max) ]
Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes. The data that is entered can be 0 bytes in length. The ANSI SQL synonym for varbinary is binary varying.
So both are equally in size (2GB). But be aware of:
Though the end of "image" datatype is still not determined, you should use the "future" proof equivalent.
But you have to ask yourself: why storing BLOBS in a Column?
For me this error occurred because I had 2 web API actions that had the exact same signatures and both had the same verbs, HttpPost
, what I did was change one of the verbs (the one used for updating) to PUT and the error was removed. The following in my catch statement helped in getting to the root of the problem:
catch (WebException webex)
{
WebResponse errResp = webex.Response;
using (Stream respStream = errResp.GetResponseStream())
{
StreamReader reader = new StreamReader(respStream);
string text = reader.ReadToEnd();
}
}
I'd like to add a more philosophical comment. The whole intent of the internet, particularly the World Wide Web, is to share data. If you don't want people to download a picture/video/document, don't put it on the web. It's really that simple. Too many people think they can impose their own rules on an existing design. Those who want to post content on the web, and control its distribution, are looking to have their cake and eat it too.
.NET has two CLRs 2.0 and 4.0. CLR 2.0 works till .NET framework 3.5. CLR 4.0 works from .NET 4.0 onwards. Its possible that your solution is using a different CLR than your reference assemblies. In your local development environment, you might have both the CLRs and hence you did not faced any problem. However when you moved to deployment environments, they might have a single CLR only and you got this error.
Pass a duration to show()
and hide()
:
When a duration is provided,
.show()
becomes an animation method.
E.g. element.delay(1000).show(0)
Here is a functional ES6 way of iterating over a NodeList
. This method uses the Array
's forEach
like so:
Array.prototype.forEach.call(element.childNodes, f)
Where f
is the iterator function that receives a child nodes as it's first parameter and the index as the second.
If you need to iterate over NodeLists more than once you could create a small functional utility method out of this:
const forEach = f => x => Array.prototype.forEach.call(x, f);
// For example, to log all child nodes
forEach((item) => { console.log(item); })(element.childNodes)
// The functional forEach is handy as you can easily created curried functions
const logChildren = forEach((childNode) => { console.log(childNode); })
logChildren(elementA.childNodes)
logChildren(elementB.childNodes)
(You can do the same trick for map()
and other Array functions.)
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
Since your example uses a generic List
, I assume you don't need an index or unique constraint on your data. A List
may contain duplicate values. If you want to insure a unique key, consider using a Dictionary<TKey, TValue>()
.
var list = new List<Tuple<int,string>>();
list.Add(Tuple.Create(1, "Andy"));
list.Add(Tuple.Create(1, "John"));
list.Add(Tuple.Create(3, "Sally"));
foreach (var item in list)
{
Console.WriteLine(item.Item1.ToString());
Console.WriteLine(item.Item2);
}
You may be interested in the csv
module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.
import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]
for row in csv.reader( lines ):
...
Try adding a semi colon to the end of your structure:
struct sotrudnik {
string name;
string speciality;
string razread;
int zarplata;
} //Semi colon here
you could use the Thread.Sleep() function
Thread.sleep(4000);
myfunction();
Your function will execute after 4 seconds. However this might pause the entire program...
Using the rewrite engine is a pretty heavyweight way to solve this problem. Here is a simpler solution:
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real server configuration
</VirtualHost>
And then you'll have another <VirtualHost>
section with ServerName www.example.com
for your real server configuration. Apache automatically preserves anything after the /
when using the Redirect
directive, which is a common misconception about why this method won't work (when in fact it does).
Now as you can see in the image below. There's a tree. Common->GDB/CDB Debugger -> Default.
Click on executable path (on the right) to find the address to gdb32.exe .
THATS IT!! This worked for me.
This can be done using REGEXP_SUBSTR easily.
Please use
REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1)
where STRING_EXAMPLE is your string.
Try:
SELECT
REGEXP_SUBSTR('STRING_EXAMPLE','[^_]+',1,1)
from dual
It will solve your problem.
Date long getTime()
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
//test if date1 is before date2
if(date1.getTime() < date2.getTime()) {
....
}
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
I solved this problem by creating separate asp.net ajax solution and copy and paste all ajax configuration from web.config to working project.
here are the must configuration you should set in web.config
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</configSections>
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</assemblies>
</compilation>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
Swift 5 Extension
This can be used as a Extension and called with: UIApplication.topSafeAreaHeight
extension UIApplication {
static var topSafeAreaHeight: CGFloat {
var topSafeAreaHeight: CGFloat = 0
if #available(iOS 11.0, *) {
let window = UIApplication.shared.windows[0]
let safeFrame = window.safeAreaLayoutGuide.layoutFrame
topSafeAreaHeight = safeFrame.minY
}
return topSafeAreaHeight
}
}
Extension of UIApplication is optional, can be an extension of UIView or whatever is preferred, or probably even better a global function.
Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:
public class Album
{
// Note that we make the setter 'private'
public string Name { get; private set; }
public string Artist { get; private set; }
public int Year { get; private set; }
public Album(string name, string artist, int year)
{
this.Name = name;
this.Artist = artist;
this.Year = year;
}
}
If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:
new {
Name = "Some Name",
Artist = "Some Artist",
Year = 1994
};
the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const
(C++) or final
(Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.
That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:
public void Configure(ConfigurationSetup setup);
and I have a class that has a number of members such as:
class ConfigurationSetup {
public String Name { get; set; }
public String Location { get; set; }
public Int32 Size { get; set; }
public DateTime Time { get; set; }
// ... and some other configuration stuff...
}
Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name
and Location
, I can just do:
ConfigurationSetup setup = new ConfigurationSetup {
Name = "Some Name",
Location = "San Jose"
};
and this allows me to set up some combination without having to define a new constructor for every possibly permutation.
On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.
You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).
As simple as:
JSON.stringify(yourData)
You should encode you data in JSON before sending it, you can't just send an object like this as POST data.
I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:
$.post(_saveDeviceUrl, {
data : $.toJSON(postData)
}, function(response){
//Process your response here
}
);
Old question, but hopefully this'll help someone else.
In my case I was using a toolchain on Ubuntu 12.04 that was built on Ubuntu 10.04 (requires GCC 4.1 to build). As most of the libraries have moved to multiarch dirs, it couldn't find ld.so. So, make a symlink for it.
Check required path:
$ readelf -a arm-linux-gnueabi-gcc | grep interpreter: [Requesting program interpreter: /lib/ld-linux-x86-64.so.2]
Create symlink:
$ sudo ln -s /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib/ld-linux-x86-64.so.2
If you're on 32bit, it'll be i386-linux-gnu and not x86_64-linux-gnu.
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives.
The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods.
As an example, a very simple page (let's call it foo.jsp):
<html>
<head/>
<body>
<%!
String someOutput() {
return "Some output";
}
%>
<% someOutput(); %>
</body>
</html>
would end up looking something like this (with a lot of the detail ignored for clarity):
public final class foo_jsp
{
// This is where the request comes in
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
// JspWriter instance is gotten from a factory
// This is why you can use 'out' directly in scriptlets
JspWriter out = ...;
// Snip
out.write("<html>");
out.write("<head/>");
out.write("<body>");
out.write(someOutput()); // i.e. write the results of the method call
out.write("</body>");
out.write("</html>");
}
// Directive gets translated as separate method - note
// there is no 'out' variable declared in scope
private String someOutput()
{
return "Some output";
}
}
docker volume create pgdata
or you can set it to the compose file
version: "3"
services:
db:
image: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgress
- POSTGRES_DB=postgres
ports:
- "5433:5432"
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- suruse
volumes:
pgdata:
It will create volume name pgdata and mount this volume to container's path.
docker volume inspect pgdata
// output will be
[
{
"Driver": "local",
"Labels": {},
"Mountpoint": "/var/lib/docker/volumes/pgdata/_data",
"Name": "pgdata",
"Options": {},
"Scope": "local"
}
]
Add <!doctype html>
at the top of your HTML output.
You can utilize the dependency management mechanism.
If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.
I'm not sure if that really saves you any code, but it is a cleaner solution IMO.
This is actually on the main page of nltk.org:
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
For me, this started happening on a project that was working, but then one day I got this error. I tried all suggestions around the .vs folder, applicationhost.config file, changing ports, restarting VS, rebooting Windows, reinstalling IIS Express. Nothing worked. I even created a new bare-bones web app, and got the same error. I have a feeling the IT department made some kind of change to my system.
After I try to run the project and IIS Express has started, in my elevated cmd prompt I run netstat -ano |find "44312"
where 44312 is the port number of my web application. I noticed what's returned is not the usual localhost IP (127.0.0.1). It was some external IP. It tells me IIS Express using a different IP.
Then I ran netsh http show iplisten
and I see that same IP in the results. netsh http delete iplisten [external ip]
, and BOOM! the web app loads!
To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:
Lets say you want the save
button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu
method of the Fragment where you view the items:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.findItem(R.id.action_save_item).setVisible(false);
}
}
NOTE: For this to work, you need the onCreate()
method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true)
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Might not be the best option, but it works and it's simple.
The problem was that you were using .src
without needing it and
you also needed to differentiate which img
you wanted to change.
function changeImage(a, imgid) {
document.getElementById(imgid).src=a;
}
<div id="main_img">
<img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
<img id="1" src='1772031_29_t.jpg' onclick='changeImage("1772031_29_b.jpg", "1");'>
<img id="2" src='1772031_55_t.jpg' onclick='changeImage("1772031_55_b.jpg", "2");'>
<img id="3" src='1772031_53_t.jpg' onclick='changeImage("1772031_53_b.jpg", "3");'>
</div>
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
For more details see these links :
1). http://developer.android.com/reference/android/content/Intent.html
2) http://developer.android.com/guide/topics/intents/intents-filters.html
3). http://www.vogella.de/articles/AndroidIntent/article.html
there are many more articles are available.
You could always iterate over a copy of the list, leaving you free to modify the original:
for item in list(somelist):
...
somelist.remove(item)
In my case namespaces
parameter was not matching the namespace of the controller.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Web.Areas.Admin.Controllers" }
);
}
Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples
Also, you should really really really change your List
into a strongly typed list (List<T>
), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.
>>> ord('a')
97
>>> chr(97)
'a'
the simplest way:
sudo docker cp path/on/your/machine adam_ubuntu:/root/path_in_container
Note putting into the root path if you are copying something that needs to be picked up by the root using ~.
You could also add the subdirectory to your Python path so that it imports as a normal script.
import sys
sys.path.insert(0, <path to dirFoo>)
import Bar
Use this query to create the new table with the values from existing table
CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name;
Now you can get all the values from existing table into newly created table.
Creating a single combined plot with your current data set up would look something like this
p <- ggplot() +
# blue plot
geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
colour="darkblue", size=1) +
# red plot
geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) +
geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
colour="red", size=1)
however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner
visual1$group <- 1
visual2$group <- 2
visual12 <- rbind(visual1, visual2)
p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
geom_point() +
geom_smooth(size=1)
Docker for Mac (Beta)
~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/log/d??ocker.log
I wrote a bash script that should automate the process written by Yakov Fain below. It can be called like ./removeComponent myComponentName This has only been tested with Angular 6
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Input a component to delete"
exit 1
fi
# finds folder with component name and deletes
find . -type d -name $1 | xargs rm -rf
# removes lines referencing the component from app.module.ts
grep -v $1 app.module.ts > temp
mv temp app.module.ts
componentName=$1
componentName+="Component"
grep -v -i $componentName app.module.ts > temp
mv temp app.module.ts
This solution is simple for Asp.net MCV 5.
Create a static class, for example Utilitarios.cs
.
Inside the Class create a static method:
public static string IsLinkActive(this UrlHelper url, string action, string controller)
{
if (url.RequestContext.RouteData.Values["controller"].ToString() == controller &&
url.RequestContext.RouteData.Values["action"].ToString() == action)
{
return "active";
}
return "";
}
call like this
<ul class="sidebar-menu" data-widget="tree">
<li class="header">HEADER</li>
<li class="@Url.IsLinkActive("Index", "Home")">
<a href="@Url.Action("Index", "Home")"><i class="fa fa-link"></i> <span>Home</span></a>
</li>
<li class="@Url.IsLinkActive("About", "Home")">
<a href="@Url.Action("About", "Home")"><i class="fa fa-link"></i><span>About</span></a>
</li>
</ul>
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
It is also possible to declare it the following way. It's not good design, but it works.
int[] twoDimIntArray[] = new int[5][10];
function mode(){
var input = $("input").val().split(",");
var mode = [];
var m = [];
var p = [];
for(var x = 0;x< input.length;x++){
if(m.indexOf(input[x])==-1){
m[m.length]=input[x];
}}
for(var x = 0; x< m.length;x++){
p[x]=0;
for(var y = 0; y<input.length;y++){
if(input[y]==m[x]){
p[x]++;
}}}
for(var x = 0;x< p.length;x++){
if(p[x] ==(Math.max.apply(null, p))){
mode.push(m[x]);
}}
$("#output").text(mode);}
setTimeout
is a kind of Thread, it holds a operation for a given time and execute.
setTimeout(function,time_in_mills);
in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.
setTimeout(function(){console.log('your name')},3000);
Key point to remember is, what ever you want to do by using the setTimeout
method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:
setTimeout(function(){yourOtherMethod(parameter);},3000);
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
Simplest way is to cast the Object
to any
, like this:
const data = {"Ticket-1.pdf":"8e6e8255-a6e9-4626-9606-4cd255055f71.pdf","Ticket-2.pdf":"106c3613-d976-4331-ab0c-d581576e7ca1.pdf"};
const obj = <any>Object;
const values = obj.values(data).map(x => x.substr(0, x.length - 4));
const commaJoinedValues = values.join(',');
console.log(commaJoinedValues);
And voila – no compilation errors ;)
They differ in spelling only. There is no difference in what they refer to. To be technical you could say they differ in emphasis. Non blocking refers to control flow(it doesn't block.) Asynchronous refers to when the event\data is handled(not synchronously.)
For personal teams
grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj
should give you the team ID
DEVELOPMENT_TEAM = ZU88ND8437;
If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections).
You can set a default encoding-set whenever you run eclipse.exe.
-Dfile.encoding=UTF-8