You can look at using dynamic modules and classes that can do the job. The only disadvantage is that it remains loaded in the app domain. But with the version of .NET framework being used, that could change. .NET 4.0 supports collectible dynamic assemblies and hence you can recreate the classes/types dynamically.
Dude I know totally how you feel, but don't forget about inline styling. It is almost the super saiyan of the CSS specificity
So it should look something like this for you,
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
You should explicitly specify the second parameter (sheetname) as None. like this:
df = pandas.read_excel("/yourPath/FileName.xlsx", None);
"df" are all sheets as a dictionary of DataFrames, you can verify it by run this:
df.keys()
result like this:
[u'201610', u'201601', u'201701', u'201702', u'201703', u'201704', u'201705', u'201706', u'201612', u'fund', u'201603', u'201602', u'201605', u'201607', u'201606', u'201608', u'201512', u'201611', u'201604']
please refer pandas doc for more details: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
After coming back to my own question after 5 year and seeing so many people found this useful, a little update.
A string variable can be split into a list
by using the split function (it can contain similar values, set
is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
or
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
or
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
To pass the parameter you need to use resolve and inject the items in controller
$scope.Edit = function (Id) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: 'EditCtrl',
resolve: {
editId: function () {
return Id;
}
}
});
}
Now if you will use like this:
app.controller('EditCtrl', ['$scope', '$location'
, function ($scope, $location, editId)
in this case editId will be undefined. You need to inject it, like this:
app.controller('EditCtrl', ['$scope', '$location', 'editId'
, function ($scope, $location, editId)
Now it will work smooth, I face the same problem many time, once injected, everything start working!
I know this is a very old thread but I wish to post this to help those who bump into this like I did.
if you don't care about using a 3rd party script, you can use moment,js Then you can use .format() to format it to anything you want it to.
This helped me: The Owner method basically ties the window to another window in case you want extra windows with the same ones.
LoadingScreen lc = new LoadingScreen();
lc.Owner = this;
lc.Show();
Consider this as well.
this.WindowState = WindowState.Normal;
this.Activate();
No, there is no type called "byte
" in C++. What you want instead is unsigned char
(or, if you need exactly 8 bits, uint8_t
from <cstdint>
, since C++11). Note that char
is not necessarily an accurate alternative, as it means signed char
on some compilers and unsigned char
on others.
Properties
.Libraries
.Compile tab
- click Add Jar/Folder
button.Or
Libraries
.Add Jar/Folder
.If you have the suhosin extension enabled, it can prevent scripts from setting the memory limit beyond what it started with or some defined cap.
http://www.hardened-php.net/suhosin/configuration.html#suhosin.memory_limit
Try this code
<table border="1" width="100%">
<tr>
<td>Name 1</td>
<td>Name 2</td>
<td colspan="2">Name 3</td>
<td>Name 4</td>
</tr>
<tr>
<td rowspan="3">ITEM 1</td>
<td rowspan="3">ITEM 2</td>
<td>name</td>
<td>price</td>
<td rowspan="3">ITEM 4</td>
</tr>
<tr>
<td>name</td>
<td>price</td>
</tr>
<tr>
<td>name</td>
<td>price</td>
</tr>
</table>
_x000D_
UPDATE user_account student
SET (student.student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE student.user_type = 'ROLE_STUDENT';
private final String easyPuzzle ="630208010200050089109060030"+
"008006050000187000060500900"+
"09007010681002000502003097";
Bundle ePzl= new Bundle();
ePzl.putString("key", easyPuzzle);
Intent i = new Intent(MainActivity.this,AnotherActivity.class);
i.putExtras(ePzl);
startActivity(i);
Now go to AnotherActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_activity);
Bundle p = getIntent().getExtras();
String yourPreviousPzl =p.getString("key");
}
now "yourPreviousPzl" is your desired string.
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
I tried everything but still this error won't go, until I changed my JDK version.
My JDK version was 7, and after I changed it to 8, the error went away, you can try it if nothing else works.
A more detailed explanation. In your model, add:
def as_dict(self):
return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
The str()
is for python 3 so if using python 2 use unicode()
. It should help deserialize dates. You can remove it if not dealing with those.
You can now query the database like this
some_result = User.query.filter_by(id=current_user.id).first().as_dict()
First()
is needed to avoid weird errors. as_dict()
will now deserialize the result. After deserialization, it is ready to be turned to json
jsonify(some_result)
The single " | " operator will evaluate both sides of the expression.
if (ActionsLogWriter.Close | ErrorDumpWriter.Close == true)
{
// Do stuff here
}
The double operator " || " will only evaluate the left side if the expression returns true.
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
C# has many similarities to C++ but their still are differences between the two languages ;)
in the same vein....
import platform
is_windows=(platform.system().lower().find("win") > -1)
if(is_windows): lv_dll=LV_dll("my_so_dll.dll")
else: lv_dll=LV_dll("./my_so_dll.so")
I'm going to approach this as if you have a Users model:
Users.cs
public class Users
{
[Key]
public int UserId { get; set; }
[Required]
public string UserName { get; set; }
public int RoleId { get; set; }
[ForeignKey("RoleId")]
public virtual DbUserRoles DbUserRoles { get; set; }
}
and a DbUserRoles model that represented a table by that name in the database:
DbUserRoles.cs
public partial class DbUserRoles
{
[Key]
public int UserRoleId { get; set; }
[Required]
[StringLength(30)]
public string UserRole { get; set; }
}
Once you had that cleaned up, you should just be able to create and fill a collection of UserRoles, like this, in your Controller:
var userRoleList = GetUserRolesList();
ViewData["userRoles"] = userRolesList;
and have these supporting functions:
private static SelectListItem[] _UserRolesList;
/// <summary>
/// Returns a static category list that is cached
/// </summary>
/// <returns></returns>
public SelectListItem[] GetUserRolesList()
{
if (_UserRolesList == null)
{
var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
{
Text = a.UserRole,
Value = a.UserRoleId.ToString()
}).ToList();
userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
_UserRolesList = userRoles.ToArray();
}
// Have to create new instances via projection
// to avoid ModelBinding updates to affect this
// globally
return _UserRolesList
.Select(d => new SelectListItem()
{
Value = d.Value,
Text = d.Text
})
.ToArray();
}
Repository.cs
My Repository function GetAllUserRoles()
for the function, above:
public class Repository
{
Model1 db = new Model1(); // Entity Framework context
// User Roles
public IList<DbUserRoles> GetAllUserRoles()
{
return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
}
}
AddNewUser.cshtml
Then do this in your View:
<table>
<tr>
<td>
@Html.EditorFor(model => model.UserName,
htmlAttributes: new { @class = "form-control" }
)
</td>
<td>
@Html.DropDownListFor(model => model.RoleId,
new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
htmlAttributes: new { @class = "form-control" }
)
</td>
</tr>
</table>
In Visual Studio menu:
Website -> Start Options -> build tab -> Select Target Framework in Dropdown box (.NET FrameWork 4)
There's no need to manually set the colors. Instead, specify a grayscale colormap...
import numpy as np
import matplotlib.pyplot as plt
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()
plt.show()
Or, if you'd prefer a wider range of colormaps, you can also specify the cmap
kwarg to scatter
. To use the reversed version of any of these, just specify the "_r
" version of any of them. E.g. gray_r
instead of gray
. There are several different grayscale colormaps pre-made (e.g. gray
, gist_yarg
, binary
, etc).
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()
You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.
C:\Users\<Username>\AppData\Local\Continuum\anaconda2
For me this was the default installation directory on Windows 7. Found it via Rusy's answer
Check This Example
Html:
<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
Javascript:
$('#showall').click(function(){
$('div').show();
});
$('#showdiv1').click(function(){
$('div[id^=div]').hide();
$('#div1').show();
});
$('#showdiv2').click(function(){
$('div[id^=div]').hide();
$('#div2').show();
});
$('#showdiv3').click(function(){
$('div[id^=div]').hide();
$('#div3').show();
});
$('#showdiv4').click(function(){
$('div[id^=div]').hide();
$('#div4').show();
});
That would be my solution:
const filterObject = (obj, condition) => {
const filteredObj = {};
Object.keys(obj).map(key => {
if (condition(key)) {
dataFiltered[key] = obj[key];
}
});
return filteredObj;
}
That's an old thread, but in case you want to upload the image having same extension-
$image = $request->image;
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = str_replace(' ', '+', $imageInfo[1]);
$imageName = "post-".time().".".$imgExt;
Storage::disk('public_feeds')->put($imageName, base64_decode($image));
You can create 'public_feeds' in laravel's filesystem.php-
'public_feeds' => [
'driver' => 'local',
'root' => public_path() . '/uploads/feeds',
],
public class CustomJsonObjectRequest extends JsonObjectRequest
{
public CustomJsonObjectRequest(int method, String url, JSONObject jsonRequest,Response.Listener listener, Response.ErrorListener errorListener)
{
super(method, url, jsonRequest, listener, errorListener);
}
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("AppId", "xyz");
return headers;
}
}
Edit - 20 March 2016
Mongoose now support timestamps for collections.
Please consider the answer of @bobbyz below. Maybe this is what you are looking for.
Mongoose supports a Date
type (which is basically a timestamp):
time : { type : Date, default: Date.now }
With the above field definition, any time you save a document with an unset time
field, Mongoose will fill in this field with the current time.
The problem with Kersnowski's approach is that when the cell is redrawn the changes made when it's selected/deselected will be gone. So I would move the changes into the cell itself, which means subclassing is required here. For example:
class ICComplaintCategoryCell: UITableViewCell {
@IBOutlet var label_title: UILabel!
@IBOutlet var label_checkmark: UILabel!
override func layoutSubviews() {
super.layoutSubviews()
reload()
}
func reload() {
if isSelected {
contentView.backgroundColor = UIColor.red
}
else if isHighlighted{
contentView.backgroundColor = UIColor.red
}
else {
contentView.backgroundColor = UIColor.white
}
}
}
And in your table view delegate just call reload
:
if let cell = self.table.cellForRowAtIndexPath(path) as? ICComplaintCategoryCell {
cell.reload()
}
Updated for Swift 3+, thanks @Bogy
I ran into this issue on my Ubuntu-64 system when attempting to import fst within python as such:
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ogi/miniconda3/lib/python3.4/site-packages/pyfst-0.2.3.dev0-py3.4-linux-x86_64.egg/fst/__init__.py", line 1, in <module>
from fst._fst import EPSILON, EPSILON_ID, SymbolTable,\
ImportError: /home/ogi/miniconda3/lib/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/local/lib/libfst.so.1)
I then ran:
ogi@ubuntu:~/miniconda3/lib$ find ~/ -name "libstdc++.so.6"
/home/ogi/miniconda3/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-5-5.2.0-2/lib/libstdc++.so.6
/home/ogi/miniconda3/pkgs/libgcc-4.8.5-1/lib/libstdc++.so.6
find: `/home/ogi/.local/share/jupyter/runtime': Permission denied
ogi@ubuntu:~/miniconda3/lib$
mv /home/ogi/miniconda3/lib/libstdc++.so.6 /home/ogi/miniconda3/libstdc++.so.6.old
cp /home/ogi/miniconda3/libgcc-5-5.2.0-2/lib/libstdc++.so.6 /home/ogi/miniconda3/lib/
At which point I was then able to load the library
ogi@ubuntu:~/miniconda3/lib$ python
Python 3.4.3 |Continuum Analytics, Inc.| (default, Jun 4 2015, 15:29:08)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import fst
>>> exit()
Your virtualhost filename should be mysite.com.conf and should contain this info
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName mysite.com
ServerAlias www.mysite.com
ServerAdmin [email protected]
DocumentRoot /var/www/mysite
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
<Directory "/var/www/mysite">
Options All
AllowOverride All
Require all granted
</Directory>
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
u'AB'
is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:
L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)
AB, AB, AB, AB
There is no u''
in memory. It is just the way to represent the unicode
object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L
is equivalent to print "[%s]" % ", ".join(map(repr, L))
i.e., repr()
function is called for each list item:
print L
print "[%s]" % ", ".join(map(repr, L))
[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']
If you are working in a REPL then a customizable sys.displayhook
is used that calls repr()
on each object by default:
>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB
Don't encode to bytes. Print unicode directly.
In your specific case, I would create a Python list and use json.dumps()
to serialize it instead of using string formatting to create JSON text:
#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
for player in players]
print test
print json.dumps(test)
[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]
(But use this in rare occasions, because HTML method is PREFERRED WAY).
.container{_x000D_
position:relative;_x000D_
}_x000D_
.container::before{ _x000D_
content:"";_x000D_
width: 100%; height: 100%; position: absolute; background: black; opacity: 0.3; z-index: 1; top: 0; left: 0;_x000D_
background: black;_x000D_
}_x000D_
.container::after{ _x000D_
content: "Your Text"; position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 3; overflow: hidden; font-size: 2em; color: red; text-align: center; text-shadow: 0px 0px 5px black; background: #0a0a0a8c; padding: 5px;_x000D_
animation-name: blinking;_x000D_
animation-duration: 1s;_x000D_
animation-iteration-count: infinite;_x000D_
animation-direction: alternate;_x000D_
}_x000D_
@keyframes blinking {_x000D_
0% {opacity: 0;}_x000D_
100% {opacity: 1;}_x000D_
}
_x000D_
<div class="container">here is main content, text , <br/> images and other page details</div>
_x000D_
If you want to select particular element use below code
var gridRowData = $("<your grid name>").data("kendoGrid");
var selectedItem = gridRowData.dataItem(gridRowData.select());
var quote = selectedItem["<column name>"];
In case you have composite primary key, do like this- ALTER TABLE table_name DROP PRIMARY KEY,ADD PRIMARY KEY (col_name1, col_name2);
Assuming i understand your question.
You can get the selected row using the DataGridView.SelectedRows
Collection. If your DataGridView allows only one selected, have a look at my sample.
DataGridView.SelectedRows Gets the collection of rows selected by the user.
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
row.Cells["ColumnName"].Value
}
Schemas logically group tables, procedures, views together. All employee-related objects in the employee
schema, etc.
You can also give permissions to just one schema, so that users can only see the schema they have access to and nothing else.
I mostly use lstlistings in papers, but for coloured output (for slides) I use pygments instead.
The command I use is:
diff -qr dir1/ dir2/
It is exactly the same as Mark's :) But his answer bothered me as it uses different types of flags, and it made me look twice. Using Mark's more verbose flags it would be:
diff --brief --recursive dir1/ dir2/
I apologise for posting when the other answer is perfectly acceptable. Could not stop myself... working on being less pedantic.
According to me it'll be working fine...
Just try with this
var GetValue=$('#radiobuttonListId').find(":checked").val();
The Radiobuttonlist value to be stored on GetValue(Variable).
EDIT: iOS 11 Solution
This is the solution to my original answer (see below). When using the iOS 11 the following link format will work:
https://itunes.apple.com/us/app/appName/idAPP_ID?mt=8&action=write-review
Simply replace APP_ID
with your specific app ID. The key to make the link work is the country code. The link above uses the us
code but it actually doesn't matter which code is used. The user will automatically be redirected to his store.
iOS 11 Update:
It seems that none of the solutions presented in the other answers to get directly to the Review Page works on iOS 11.
The problem most likely is, that an app page in the iOS 11 App Store app does NOT have a Review Tab anymore. Instead the reviews are now located directly below the description and the screenshots. Of course it could still be possible to reach this section directly (e.g. with some kind of anchor), but it seems that this is not supported / intended by Apple.
Using one of the following links does not work anymore. They still bring the users to the App Store app but only to a blank page:
itms-apps://itunes.apple.com/app/idYOUR_APP_ID?action=write-review
itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=YOUR_APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software
Everyone how still uses these links should update their apps ASAP, because referring the users to a blank App Store page is most likely not what you intended.
Links which do not refer to the Review page but to the App page, still work however, e.g.
itms-apps://itunes.apple.com/app/idYOUR_APP_ID (same as above, but without write-review parameter)
So, you can still get the users to your apps Store page, but not directly to the review section anymore. Users now have to scroll down to the review section manually to leave their feedback.
Without a question this a "great and awesome benefit for User Experience and will help developers to engage users to leave high quality reviews without annoying them". Well done Apple...
Git creates a master branch once you've done your first commit. There's nothing to have a branch for if there's no code in the repository.
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
ng-click "$watch(edit($index), open())"
I had this issue where on a screen orientation change, the activity finished before the AsyncTask with the progress dialog completed. I seemed to resolve this by setting the dialog to null onPause()
and then checking this in the AsyncTask before dismissing.
@Override
public void onPause() {
super.onPause();
if ((mDialog != null) && mDialog.isShowing())
mDialog.dismiss();
mDialog = null;
}
... in my AsyncTask:
protected void onPreExecute() {
mDialog = ProgressDialog.show(mContext, "", "Saving changes...",
true);
}
protected void onPostExecute(Object result) {
if ((mDialog != null) && mDialog.isShowing()) {
mDialog.dismiss();
}
}
I met it when import a ViewController.m in TableViewController. Try to delete '#import "ViewController.m"' if it exited. Hope this help!
In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster
UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});
Below is a solution that combines a shorter application of Object.assign
to more closely model the original C#
pattern.
But first, lets review the techniques offered so far, which include:
Object.assign
Partial<T>
trick within the copy constructorObject.create
instead of Object.assign
Of course, each have their pros/cons. Modifying a target class to create a copy constructor may not always be an option. And "casting" loses any functions associated with the target type. Object.create
seems less appealing since it requires a rather verbose property descriptor map.
So, here's yet another approach that is somewhat simpler, maintains the type definition and associated function prototypes, and more closely models the intended C#
pattern:
const john = Object.assign( new Person(), {
name: "John",
age: 29,
address: "Earth"
});
That's it. The only addition over the C#
pattern is Object.assign
along with 2 parenthesis and a comma. Check out the working example below to confirm it maintains the type's function prototypes. No constructors required, and no clever tricks.
This example shows how to initialize an object using an approximation of a C#
field initializer:
class Person {_x000D_
name: string = '';_x000D_
address: string = '';_x000D_
age: number = 0;_x000D_
_x000D_
aboutMe() {_x000D_
return `Hi, I'm ${this.name}, aged ${this.age} and from ${this.address}`;_x000D_
}_x000D_
}_x000D_
_x000D_
// typescript field initializer (maintains "type" definition)_x000D_
const john = Object.assign( new Person(), {_x000D_
name: "John",_x000D_
age: 29,_x000D_
address: "Earth"_x000D_
});_x000D_
_x000D_
// initialized object maintains aboutMe() function prototype_x000D_
console.log( john.aboutMe() );
_x000D_
You can use gcd to do this without having to create another method
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(@"Do some work");
});
You should still ask yourself "do I really need to add a delay" as it can often complicate code and cause race conditions
I assume the original question included how does Express use this environment variable.
Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error
, to avoid leaking implementation details to the world.
One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.
var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]
This is solved for me when I update maven and check the option "Force update of Snapshots/Releases" in Eclipse. this clears all errors. So right click on project -> Maven -> update project, then check the above option -> Ok. Hope this helps you.
I know i'm too late for the answer but for people reading this I found a much easier way for doing it
myVariable = 'This string is supposed to be raw \'
print(r'%s' %myVariable)
I am a late comer, but maybe I can say this with a specific example:
Say, if you have a <table>
, with <tr>
, and then <td>
. Now, let's say you set 3 event handlers for the <td>
element, then if you do event.stopPropagation()
in the first event handler you set for <td>
, then all event handlers for <td>
will still run, but the event just won't propagate to <tr>
or <table>
(and won't go up and up to <body>
, <html>
, document
, and window
).
Now, however, if you use event.stopImmediatePropagation()
in your first event handler, then, the other two event handlers for <td>
WILL NOT run, and won't propagate up to <tr>
, <table>
(and won't go up and up to <body>
, <html>
, document
, and window
).
Note that it is not just for <td>
. For other elements, it will follow the same principle.
The Tesseract documentation contains some good details on how to improve the OCR quality via image processing steps.
To some degree, Tesseract automatically applies them. It is also possible to tell Tesseract to write an intermediate image for inspection, i.e. to check how well the internal image processing works (search for tessedit_write_images
in the above reference).
More importantly, the new neural network system in Tesseract 4 yields much better OCR results - in general and especially for images with some noise. It is enabled with --oem 1
, e.g. as in:
$ tesseract --oem 1 -l deu page.png result pdf
(this example selects the german language)
Thus, it makes sense to test first how far you get with the new Tesseract LSTM mode before applying some custom pre-processing image processing steps.
something like:
DELIMITER //
CREATE PROCEDURE alluser()
BEGIN
SELECT *
FROM users;
END //
DELIMITER ;
than:
SHOW CREATE PROCEDURE alluser
gives result:
'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
SELECT *
FROM users;
END'
I wanted to make a version of this that uses $.getJSON() from a separate JSON file.
Demo: here
JavaScript:
$(document).ready(function () {
"use strict";
var selectData, $states;
function updateSelects() {
var cities = $.map(selectData[this.value], function (city) {
return $("<option />").text(city);
});
$("#city_names").empty().append(cities);
}
$.getJSON("updateSelect.json", function (data) {
var state;
selectData = data;
$states = $("#us_states").on("change", updateSelects);
for (state in selectData) {
$("<option />").text(state).appendTo($states);
}
$states.change();
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<select id="us_states"></select>
<select id="city_names"></select>
<script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>
JSON:
{
"NE": [
"Smallville",
"Bigville"
],
"CA": [
"Sunnyvale",
"Druryburg",
"Vickslake"
],
"MI": [
"Lakeside",
"Fireside",
"Chatsville"
]
}
In Kotlin:
switch_button.setOnCheckedChangeListener { buttonView, isChecked ->
if (isChecked) {
// The switch enabled
text_view.text = "Switch on"
} else {
// The switch disabled
text_view.text = "Switch off"
}
}
myString.Substring(myString.Length - 3, 3)
Here are examples on substring.>>
http://www.dotnetperls.com/substring
Refer those.
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
On my network just setting http_proxy didn't work for me. The following points were relevant.
1 Setting http_proxy for your user wont be preserved when you execute sudo - to preserve it, do:
sudo -E yourcommand
I got my install working by first installing cntlm local proxy. The instructions here is succinct : http://www.leg.uct.ac.za/howtos/use-isa-proxies
Instead of student number, you'd put your domain username
2 To use the cntlm local proxy, exec:
pip install --proxy localhost:3128 pygments
Java EE is a collection of specifications for developing and deploying enterprise applications.
In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up Java EE are:
The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.
When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.
If you are developing for a modern browser, Instead of parsing the url parameters yourself- you can use the built in URL
functions to do it for you like this:
const parser = new URL(url || window.location);
parser.searchParams.set(key, value);
window.location = parser.href;
Edit your php.ini
file, search for soap.wsdl_cache_enabled
and set the value to 0
[soap]
; Enables or disables WSDL caching feature.
; http://php.net/soap.wsdl-cache-enabled
soap.wsdl_cache_enabled=0
build gradle:
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
code:
interface MyCallback {
fun someMethod(value: String)
}
class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
test:
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()
val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
Besides the removal of the github messaging service, usage was often not necessary due to many githubbers communicating with- and advocating twitter.
The advantage is that there is:
It is probably no coincidence that stackoverflow doesn't allow private messaging either, to ensure full transparency. The entire messaging issue is thoroughly discussed on meta-stackoverflow here.
You can use this.setResizable(false);
or frameObject.setResizable(false);
best way and more simple to center an iframe on your webpage is :
<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>
where width and height will be the size of your iframe in your html page.
Prolly a better solution out there somewhere, but this is what I did.
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TableRow>
<TextView
android:layout_column="1"
android:text="•"></TextView>
<TextView
android:layout_column="2"
android:layout_width="wrap_content"
android:text="First line"></TextView>
</TableRow>
<TableRow>
<TextView
android:layout_column="1"
android:text="•"></TextView>
<TextView
android:layout_column="2"
android:layout_width="wrap_content"
android:text="Second line"></TextView>
</TableRow>
</TableLayout>
It works like you want, but a workaround really.
If you want to avoid writing all of this everytime, you can define a function :
def run(filename):
exec(open(filename).read())
and then call it
run('filename.py')
If you "git pull" and it says "Already up-to-date.", and still get this error, it might be because one of your other branches isn't up to date. Try switching to another branch and making sure that one is also up-to-date before trying to "git push" again:
Switch to branch "foo" and update it:
$ git checkout foo
$ git pull
You can see the branches you've got by issuing command:
$ git branch
It's because your TextView recieve new text on every iteration and previuos value thrown away. Concatenate strings by StringBuilder and set TextView value after loop. Also you can use this type of loop:
for (Map.Entry<String, String> e : map.entrySet()) {
//to get key
e.getKey();
//and to get value
e.getValue();
}
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
Just to add that tmux
scroll buffer does not clear with clear
, reset
or printf
. You need to :clear-history
. See link.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.
After trying most of the solutions here, I finally just added a reference to the project from the click once project, this changed it to Include (Auto) from Include and it finally worked.
I have a project on GitHub that you can use
https://github.com/BrunoVT1992/ConsoleTable
You can use it like this:
var table = new Table();
table.SetHeaders("Name", "Date", "Number");
for (int i = 0; i <= 10; i++)
{
if (i % 2 == 0)
table.AddRow($"name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), i.ToString());
else
table.AddRow($"long name {i}", DateTime.Now.AddDays(-i).ToLongDateString(), (i * 5000).ToString());
}
Console.WriteLine(table.ToString());
It will give this result:
You can do this too
Before you use this you must declare the DB facade in the controller Simply put this line for that
use Illuminate\Support\Facades\DB;
Now you can get a row using this
$getUserByEmail = DB::table('users')->where('email', $email)->first();
or by this too
$getUserByEmail = DB::select('SELECT * FROM users WHERE email = ?' , ['[email protected]']);
This one returns an array with only one item in it and while the first one returns an object. Keep that in mind.
Hope this helps.
Here's another method for generating a random string:
SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 8) AS myrandomstring
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.
ngClick directive (as well as all other event directives) creates $event
variable which is available on same scope. This variable is a reference to JS event
object and can be used to call stopPropagation()
:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td>
<button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
Delete
</button>
</td>
</tr>
</table>
this worked for me on an AWS instance, to at least clear the cached memory mongo was using. after this you can see how your settings have had effect.
ubuntu@hongse:~$ free -m
total used free shared buffers cached
Mem: 3952 3667 284 0 617 514
-/+ buffers/cache: 2535 1416
Swap: 0 0 0
ubuntu@hongse:~$ sudo su
root@hongse:/home/ubuntu# sync; echo 3 > /proc/sys/vm/drop_caches
root@hongse:/home/ubuntu# free -m
total used free shared buffers cached
Mem: 3952 2269 1682 0 1 42
-/+ buffers/cache: 2225 1726
Swap: 0 0 0
The memory may be in reserve by the OS to be used for running what you normally run (kind of like a swap file). You may be able to squeeze in another app or two by
But the only very good fix might be to
Take a look at forum post It was bound to happen: low memory warning!.
The important part is:
The OS knows how much memory it needs to run the apps you already have. This is a perfect example.
Now you may be able to "fool" the OS by force closing some apps that are sitting in RAM. This will increase your "bucket" of memory which may let you install an app, but remember if you do these types of things you will only cause issues down the road.. lagg, error messages, etc. (because you are fooling the OS in thinking you have given it additional memory which in fact you did.. you only force closed).
Another good explanation of what is happening is in forum post Low Internal Memory.
The important part is:
The reason why your internal space is filling up is 3-fold. First, when an app is "moved" to the SD card, it isn't completely moved. Only portions of it actually go. Second, the Dalvik cache of the app is still stored on the internal memory (which takes up a substantial amount of space). Three, the data for apps and all your system settings are stored in the internal memory (yes, some apps use the SD card for portions of their data, but every app has data stored on the internal memory).
And the thread includes suggestions on what partitioning you can do to your SD card to allow 'moar apps'!
If you only want the position, vp.getCurrentItem()
will give it to you, no need to apply the onPageChangeListener() for that purpose alone.
At first you have to understand what does join do? We connect multiple table and get specific result from the joined tables. The simplest way to do this is cross join.
Lets say tableA has two column A and B. And tableB has three column C and D. If we apply cross join it will produce lot of meaningless row. Then we have to match using primary key to get actual data.
Left: it will return all records from left table and matched record from right table.
Right: it will return opposite to Left join. It will return all records from right table and matched records from left table.
Inner: This is like intersection. It will return only matched records from both table.
Outer: And this is like union. It will return all available record from both table.
Some times we don't need all of the data, and also we should need only common data or records. we can easily get it using these join methods. Remember left and right join also are outer join.
You can get all records just using cross join. But it could be expensive when it comes to millions of records. So make it simple by using left, right, inner or outer join.
thanks
I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.
"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.
First a method that goes from descendant coordinates to ancestor:
public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
final float scrollX = descendant.getScrollX();
final float scrollY = descendant.getScrollY();
final float left = descendant.getLeft();
final float top = descendant.getTop();
final float px = descendant.getPivotX();
final float py = descendant.getPivotY();
final float tx = descendant.getTranslationX();
final float ty = descendant.getTranslationY();
final float sx = descendant.getScaleX();
final float sy = descendant.getScaleY();
point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
point[1] = top + py + (point[1] - py) * sy + ty - scrollY;
ViewParent parent = descendant.getParent();
if (descendant != ancestor && parent != ancestor && parent instanceof View) {
transformToAncestor(point, ancestor, (View) parent);
}
}
Next the inverse, from ancestor to descendant:
public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
ViewParent parent = descendant.getParent();
if (descendant != ancestor && parent != ancestor && parent instanceof View) {
transformToDescendant(point, ancestor, (View) parent);
}
final float scrollX = descendant.getScrollX();
final float scrollY = descendant.getScrollY();
final float left = descendant.getLeft();
final float top = descendant.getTop();
final float px = descendant.getPivotX();
final float py = descendant.getPivotY();
final float tx = descendant.getTranslationX();
final float ty = descendant.getTranslationY();
final float sx = descendant.getScaleX();
final float sy = descendant.getScaleY();
point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}
I was looking for a solution to remove strings' masks, specifically from Brazilian phones numbers, this post not answered but inspired me. This is my solution:
>>> phone_number = '+55(11)8715-9877'
>>> ''.join([n for n in phone_number if n.isdigit()])
'551187159877'
If all you want to do is remove the changes made in revision 3, you might want to use git revert.
Git revert simply creates a new revision with changes that undo all of the changes in the revision you are reverting.
What this means, is that you retain information about both the unwanted commit, and the commit that removes those changes.
This is probably a lot more friendly if it's at all possible the someone has pulled from your repository in the mean time, since the revert is basically just a standard commit.
This is a C++ interview test question not homework.
Then your interviewer needs to refresh his recollection with how the C++ standard works. And I quote:
For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration.
The whole "whose underlying type is not fixed" part is from C++11, but the rest is all standard C++98/03. In short, the sizeof(months_t)
is not 4. It is not 2 either. It could be any of those. The standard does not say what size it should be; only that it should be big enough to fit any enumerator.
why the all size is 4 bytes ? not 12 x 4 = 48 bytes ?
Because enums are not variables. The members of an enum are not actual variables; they're just a semi-type-safe form of #define. They're a way of storing a number in a reader-friendly format. The compiler will transform all uses of an enumerator into the actual numerical value.
Enumerators are just another way of talking about a number. january
is just shorthand for 0
. And how much space does 0 take up? It depends on what you store it in.
Please note that the tr -s ' '
option will not remove any single leading spaces. If your column is right-aligned (as with ps
pid)...
$ ps h -o pid,user -C ssh,sshd | tr -s " "
1543 root
19645 root
19731 root
Then cutting will result in a blank line for some of those fields if it is the first column:
$ <previous command> | cut -d ' ' -f1
19645
19731
Unless you precede it with a space, obviously
$ <command> | sed -e "s/.*/ &/" | tr -s " "
Now, for this particular case of pid numbers (not names), there is a function called pgrep
:
$ pgrep ssh
However, in general it is actually still possible to use shell functions in a concise manner, because there is a neat thing about the read
command:
$ <command> | while read a b; do echo $a; done
The first parameter to read, a
, selects the first column, and if there is more, everything else will be put in b
. As a result, you never need more variables than the number of your column +1.
So,
while read a b c d; do echo $c; done
will then output the 3rd column. As indicated in my comment...
A piped read will be executed in an environment that does not pass variables to the calling script.
out=$(ps whatever | { read a b c d; echo $c; })
arr=($(ps whatever | { read a b c d; echo $c $b; }))
echo ${arr[1]} # will output 'b'`
So we then end up with the answer by @frayser which is to use the shell variable IFS which defaults to a space, to split the string into an array. It only works in Bash though. Dash and Ash do not support it. I have had a really hard time splitting a string into components in a Busybox thing. It is easy enough to get a single component (e.g. using awk) and then to repeat that for every parameter you need. But then you end up repeatedly calling awk on the same line, or repeatedly using a read block with echo on the same line. Which is not efficient or pretty. So you end up splitting using ${name%% *}
and so on. Makes you yearn for some Python skills because in fact shell scripting is not a lot of fun anymore if half or more of the features you are accustomed to, are gone. But you can assume that even python would not be installed on such a system, and it wasn't ;-).
Put a z-indez
of -1
on your absolute (or relative) positioned element.
This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
if (!$_FILES['image']['size'][0] == 0){ //}
Use TOP 1
if the query returns multiple rows.
SELECT TOP 1 @ModelID = m.modelid
FROM MODELS m
WHERE m.areaid = 'South Coast'
Three Answers :
Simple :
<img>
<xsl:attribute name="src">
<xsl:value-of select="//your/xquery/path"/>
<xsl:value-of select="'vmLogo.gif'"/>
</xsl:attribute>
</img>
Using 'concat' :
<img>
<xsl:attribute name="src">
<xsl:value-of select="concat(//your/xquery/path,'vmLogo.gif')"/>
</xsl:attribute>
</img>
Attribute shortcut as suggested by @TimC
<img src="{concat(//your/xquery/path,'vmLogo.gif')}" />
REST webservice: (http://localhost:8080/your-app/rest/data/post)
package com.yourorg.rest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/data")
public class JSONService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(String data) {
String result = "Data post: "+data;
return Response.status(201).entity(result).build();
}
Client send a post:
package com.yourorg.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");
String input = "{\"message\":\"Hello\"}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When you do new Promise((resolve)...
the type inferred was Promise<{}>
because you should have used new Promise<number>((resolve)
.
It is interesting that this issue was only highlighted when the async
keyword was added. I would recommend reporting this issue to the TS team on GitHub.
There are many ways you can get around this issue. All the following functions have the same behavior:
const whatever1 = () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever2 = async () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever3 = async () => {
return await new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever4 = async () => {
return Promise.resolve(4);
};
const whatever5 = async () => {
return await Promise.resolve(4);
};
const whatever6 = async () => Promise.resolve(4);
const whatever7 = async () => await Promise.resolve(4);
In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>
.
Your fragment class should implement OnClickListener
public class SmartTvControllerFragment extends Fragment implements View.OnClickListener
Then get view, link button and set onClickListener like in example below
View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.smart_tv_controller_fragment, container, false);
upButton = (Button) view.findViewById(R.id.smart_tv_controller_framgment_up_button);
upButton.setOnClickListener(this);
return view;
}
And then add onClickListener method and do what you want.
@Override
public void onClick(View v) {
//do what you want to do when button is clicked
switch (v.getId()) {
case R.id.textView_help:
switchFragment(HelpFragment.TAG);
break;
case R.id.textView_settings:
switchFragment(SettingsFragment.TAG);
break;
}
}
This is my example of code, but I hope you understood
I have same problem for image which is not showing correctly in outlook.and I am using px and % for applying height and width for image. but when i removed px and % and using only just whatever the value in html it is worked for me. For example i was using : width="800px" now I'm using widht="800" and problem is resolved for me.
Seem to Junit jar file is not in path also make sure you are using jdk1.5 or above.
@neilfws's solution works great for data.frame
s, but not for data.table
s since they lack the row.names
property. This approach works for both:
df.expanded <- df[rep(seq(nrow(df)), df$freq), 1:2]
The code for data.table
is a tad cleaner:
# convert to data.table by reference
setDT(df)
df.expanded <- df[rep(seq(.N), freq), !"freq"]
I have setup a DataFrame
with a few simple strings in it's columns:
>>> df
a b
0 a g
1 b h
2 d a
3 e e
You can concatenate the columns you are interested in and call unique
function:
>>> pandas.concat([df['a'], df['b']]).unique()
array(['a', 'b', 'd', 'e', 'g', 'h'], dtype=object)
GroupBy using in Hibernate
This is the resulting code
public Map getStateCounts(final Collection ids) {
HibernateSession hibernateSession = new HibernateSession();
Session session = hibernateSession.getSession();
Criteria criteria = session.createCriteria(DownloadRequestEntity.class)
.add(Restrictions.in("id", ids));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("state"));
projectionList.add(Projections.rowCount());
criteria.setProjection(projectionList);
List results = criteria.list();
Map stateMap = new HashMap();
for (Object[] obj : results) {
DownloadState downloadState = (DownloadState) obj[0];
stateMap.put(downloadState.getDescription().toLowerCase() (Integer) obj[1]);
}
hibernateSession.closeSession();
return stateMap;
}
If you have the HTML
<form name="formname" .... id="form-first">
<iframe id="one" src="iframe2.html">
</iframe>
</form>
and JavaScript
function iframeRef( frameRef ) {
return frameRef.contentWindow
? frameRef.contentWindow.document
: frameRef.contentDocument
}
var inside = iframeRef( document.getElementById('one') )
inside
is now a reference to the document, so you can do getElementsByTagName('textarea')
and whatever you like, depending on what's inside the iframe src.
Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing
property on yer h4
tags like this.
h4 {
-webkit-font-smoothing: antialiased;
}
You can also use subpixel-antialiased
, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.
Try putting it in a span element:
<div id='page' style='width: 600px'>_x000D_
<h1><span style='border:2px black solid; font-size:42px;'>Title</span></h1>_x000D_
</div>
_x000D_
Beside the obvious reloadData from UI/Main Thread (whatever Apple calls it), in my case, I had forgotten to also update the SECTIONS info. Therefor it did not detect any new sections!
I was facing the error
"Unable to create an object of type 'MyContext'. Add an implementation of 'IDesignTimeDbContextFactory' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."
This is how my problem was solved. Run the below command while you are in your solution directory
dotnet ef migrations add InitialMigration --project "Blog.Infrastructure" --startup-project "Blog.Appication"
Here Application is my startup project containing the Startup.cs class & Infrastructure is my project containing the DbContext class.
then run update using the same structure.
dotnet ef database update --project "Blog.Infrastructure" --startup-project "Blog.Application"
For Mysql5.7, login in mysql command line and run the command,
mysql> show variables like 'sql_mode' ;
It will show that NO_ZERO_IN_DATE,NO_ZERO_DATE in sql_mode.
Try to add a line below [mysqld] in your mysql conf file to remove the two option, mine(mysql 5.7 on Ubuntu 16) is /etc/mysql/mysql.conf.d/mysqld.cnf
Now restart mysql. It works!
Whenever you pass a string of HTML to any of jQuery's methods, this is what happens:
A temporary element is created, let's call it x. x's innerHTML
is set to the string of HTML that you've passed. Then jQuery will transfer each of the produced nodes (that is, x's childNodes
) over to a newly created document fragment, which it will then cache for next time. It will then return the fragment's childNodes
as a fresh DOM collection.
Note that it's actually a lot more complicated than that, as jQuery does a bunch of cross-browser checks and various other optimisations. E.g. if you pass just <div></div>
to jQuery()
, jQuery will take a shortcut and simply do document.createElement('div')
.
EDIT: To see the sheer quantity of checks that jQuery performs, have a look here, here and here.
innerHTML
is generally the faster approach, although don't let that govern what you do all the time. jQuery's approach isn't quite as simple as element.innerHTML = ...
-- as I mentioned, there are a bunch of checks and optimisations occurring.
The correct technique depends heavily on the situation. If you want to create a large number of identical elements, then the last thing you want to do is create a massive loop, creating a new jQuery object on every iteration. E.g. the quickest way to create 100 divs with jQuery:
jQuery(Array(101).join('<div></div>'));
There are also issues of readability and maintenance to take into account.
This:
$('<div id="' + someID + '" class="foobar">' + content + '</div>');
... is a lot harder to maintain than this:
$('<div/>', {
id: someID,
className: 'foobar',
html: content
});
You can also keep adding strings to an existing string like so:
var myString = "Hello ";
myString += "World";
myString += "!";
the result would be -> Hello World!
http://pypi.python.org/pypi/websocket-client/
Ridiculously easy to use.
sudo pip install websocket-client
Sample client code:
#!/usr/bin/python
from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Receiving..."
result = ws.recv()
print "Received '%s'" % result
ws.close()
Sample server code:
#!/usr/bin/python
import websocket
import thread
import time
def on_message(ws, message):
print message
def on_error(ws, error):
print error
def on_close(ws):
print "### closed ###"
def on_open(ws):
def run(*args):
for i in range(30000):
time.sleep(1)
ws.send("Hello %d" % i)
time.sleep(1)
ws.close()
print "thread terminating..."
thread.start_new_thread(run, ())
if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://echo.websocket.org/",
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
ws.run_forever()
http://www.cplusplus.com/reference/clibrary/cstring/strtok/
Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.
From the website:
char * strtok ( char * str, const char * delimiters );
On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.
Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.
Parameters
- str
- C string to truncate.
- Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
- delimiters
- C string containing the delimiter characters.
- These may vary from one call to another.
Return Value
A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.
Example
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
You can also use :=
construct to assign and decide on action in one step. Consider following example:
# Example of setting default server and reporting it's status
server=$1
if [[ ${server:=localhost} =~ [a-z] ]] # 'localhost' assigned here to $server
then echo "server is localhost" # echo is triggered since letters were found in $server
else
echo "server was set" # numbers were passed
fi
If $1
is not empty, localhost
will be assigned to server
in the if
condition field, trigger match and report match result. In this way you can assign on the fly and trigger appropriate action.
Use the hashchange
event:
window.addEventListener("hashchange", function(e) {
// ...
})
If you need to support older browsers, check out the hashChange
Event section in Modernizr's HTML5 Cross Browser Polyfills wiki page.
In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:
Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"
In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… />
as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head>
section
<link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
In your server.js file, you need to use the app.use()
middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use()
middleware there is already a function/method provided by express called express.static()
. Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:
// using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
// app.use("/route", express.static("foldername"));
app.use('/public', express.static('public'));
After following these simple 3 steps, every time you res.render('ejsfile')
in your app.get()
methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.
#!usr/bin/python3
def prime_check(*args):
for arg in args:
if arg > 1: # prime numbers are greater than 1
for i in range(2,arg): # check for factors
if(arg % i) == 0:
print(arg,"is not Prime")
print(i,"times",arg//i,"is",arg)
break
else:
print(arg,"is Prime")
# if input number is less than
# or equal to 1, it is not prime
else:
print(arg,"is not Prime")
return
# Calling Now
prime_check(*list(range(101))) # This will check all the numbers in range 0 to 100
prime_check(#anynumber) # Put any number while calling it will check.
The only thing which works with no side-effects is to create a custom back button. As long as you don't provide a custom action, even the slide gesture works.
extension UIViewController {
func setupBackButton() {
let customBackButton = UIBarButtonItem(title: " ", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = customBackButton
}}
Unfortunately, if you want all back buttons in the not to have any titles, you need to setup this custom back button in all your view controllers :/
override func viewDidLoad() {
super.viewDidLoad()
setupBackButton()
}
It is very important you set a whitespace as the title and not the empty string.
For MySQL Workbench 8.0 navigate to:
Server > Data Import
A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.
Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.
Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.
That's it!
For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard
Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.
Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.
If you want to disable client side validation for a form in HTML5 add a novalidate attribute to the form element. Ex:
<form method="post" action="/foo" novalidate>...</form>
See https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-novalidate
scope - https://www.googleapis.com/auth/userinfo.profile
return youraccess_token = access_token
get https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=youraccess_token
you will get json:
{
"id": "xx",
"name": "xx",
"given_name": "xx",
"family_name": "xx",
"link": "xx",
"picture": "xx",
"gender": "xx",
"locale": "xx"
}
To Tahir Yasin:
This is a php example.
You can use json_decode function to get userInfo array.
$q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=xxx';
$json = file_get_contents($q);
$userInfoArray = json_decode($json,true);
$googleEmail = $userInfoArray['email'];
$googleFirstName = $userInfoArray['given_name'];
$googleLastName = $userInfoArray['family_name'];
DO NOT USE THIS ANSWER. I HAVE ONLY LEFT IT FOR HISTORICAL PURPOSES. SEE THE COMMENTS BELOW.
There is a simple trick if it is a BOOL parameter.
Pass nil for NO and self for YES. nil is cast to the BOOL value of NO. self is cast to the BOOL value of YES.
This approach breaks down if it is anything other than a BOOL parameter.
Assuming self is a UIView.
//nil will be cast to NO when the selector is performed
[self performSelector:@selector(setHidden:) withObject:nil afterDelay:5.0];
//self will be cast to YES when the selector is performed
[self performSelector:@selector(setHidden:) withObject:self afterDelay:10.0];
You don't need to use a property for that. Just override __setattr__
to make them read only.
class C(object):
def __init__(self, keys, values):
for (key, value) in zip(keys, values):
self.__dict__[key] = value
def __setattr__(self, name, value):
raise Exception("It is read only!")
Tada.
>>> c = C('abc', [1,2,3])
>>> c.a
1
>>> c.b
2
>>> c.c
3
>>> c.d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'd'
>>> c.d = 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __setattr__
Exception: It is read only!
>>> c.a = 'blah'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __setattr__
Exception: It is read only!
Or even simpler...
Arguments in !
Parameters out !
else if (isset($_GET['actie']) && $_GET['actie']== "aanmelden"){
$username= $_POST['username'];
$password= md5($_POST['password']);
$query = "SELECT password FROM tbl WHERE username = '$username'";
$result= mysql_query($query);
$row= mysql_fetch_array($result);
if($password == $row['password']){
session_start();
$_SESSION['logged in'] = true;
echo "Logged in";
}
}
Swift 4 answer based on helpful answer from @mbm29414.
Unfortunately, it requires the use of a XIB file. There doesn't appear to be an alternative.
The key parts are using a sizing cell (created only once) and registering the XIB when initializing the collection view.
Then you size each cell dynamically within the sizeForItemAt
function.
// UICollectionView Vars and Constants
let CellXIBName = YouViewCell.XIBName
let CellReuseID = YouViewCell.ReuseID
var sizingCell = YouViewCell()
fileprivate func initCollectionView() {
// Connect to view controller
collectionView.dataSource = self
collectionView.delegate = self
// Register XIB
collectionView.register(UINib(nibName: CellXIBName, bundle: nil), forCellWithReuseIdentifier: CellReuseID)
// Create sizing cell for dynamically sizing cells
sizingCell = Bundle.main.loadNibNamed(CellXIBName, owner: self, options: nil)?.first as! YourViewCell
// Set scroll direction
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
collectionView.collectionViewLayout = layout
// Set properties
collectionView.alwaysBounceVertical = true
collectionView.alwaysBounceHorizontal = false
// Set top/bottom padding
collectionView.contentInset = UIEdgeInsets(top: collectionViewTopPadding, left: collectionViewSidePadding, bottom: collectionViewBottomPadding, right: collectionViewSidePadding)
// Hide scrollers
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
// Get cell data and render post
let data = YourData[indexPath.row]
sizingCell.renderCell(data: data)
// Get cell size
sizingCell.setNeedsLayout()
sizingCell.layoutIfNeeded()
let cellSize = sizingCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
// Return cell size
return cellSize
}
This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.
Since iOS 9, you need to add "App Transport Security Settings" to your info.plist file and allow "Allow Arbitrary Loads" before making request to non-secure HTTP web service. I had this issue in one of my app.
Edit: As per the Mr Me comment on this answer, it looks like compression is now available for JPG/WebP formats ( see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL ).
As far as I know, you cannot compress images using canvas, instead, you can resize it. Using canvas.toDataURL will not let you choose the compression ratio to use. You can take a look at canimage that does exactly what you want : https://github.com/nfroidure/CanImage/blob/master/chrome/canimage/content/canimage.js
In fact, it's often sufficient to just resize the image to decrease it's size but if you want to go further, you'll have to use newly introduced method file.readAsArrayBuffer to get a buffer containing the image data.
Then, just use a DataView to read it's content according to the image format specification (http://en.wikipedia.org/wiki/JPEG or http://en.wikipedia.org/wiki/Portable_Network_Graphics).
It'll be hard to deal with image data compression, but it is worse a try. On the other hand, you can try to delete the PNG headers or the JPEG exif data to make your image smaller, it should be easier to do so.
You'll have to create another DataWiew on another buffer and fill it with the filtered image content. Then, you'll just have to encode you're image content to DataURI using window.btoa.
Let me know if you implement something similar, will be interesting to go through the code.
Hilarious. I nearly posted the same question a few days ago due to the same damn game! I did not however because just searched google for boggle solver python and got all the answers I could want.
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("images/background.png"),
fit: BoxFit.cover
),
),
this also works inside a container.
I figured out mistake here use double quotations instead of single quotations.
change this
git commit -m 'initial commit'
to
git commit -m "initial commit"
I know this is old, but I've tested this in many ways and it hasn't let me down yet, unless someone can tell me otherwise.
Row number
Row = ws.Cells.Find(What:="*", After:=[A1] , SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Column Letter
ColumnLetter = Split(ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Cells.Address(1, 0), "$")(0)
Column Number
ColumnNumber = ws.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Method to read JSON file from Assets folder and return as a string object.
public static String getAssetJsonData(Context context) {
String json = null;
try {
InputStream is = context.getAssets().open("myJson.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
Log.e("data", json);
return json;
}
Now for parsing data in your activity:-
String data = getAssetJsonData(getApplicationContext());
Type type = new TypeToken<Your Data model>() {
}.getType();
<Your Data model> modelObject = new Gson().fromJson(data, type);
Faced this issue on Mac:
I have tried different solution, But below works for me -
adb kill-server
adb start-server
adb devices
, It will work and display you all connected devices.Hope it helps !
There used to be a statement in the SQLite documentation that the practical size limit of a database file was a few dozen GB:s. That was mostly due to the need for SQLite to "allocate a bitmap of dirty pages" whenever you started a transaction. Thus 256 byte of RAM were required for each MB in the database. Inserting into a 50 GB DB-file would require a hefty (2^8)*(2^10)=2^18=256 MB of RAM.
But as of recent versions of SQLite, this is no longer needed. Read more here.
use this(assume that your table name is emails):
select * from emails as a
inner join
(select EmailAddress, min(Id) as id from emails
group by EmailAddress ) as b
on a.EmailAddress = b.EmailAddress
and a.Id = b.id
hope this help..
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
Your transfer speed is likely not to be limited by Java. Instead I would suspect (in no particular order)
If you read the complete dataset and then write it out to disk, then that will take longer, since the JVM will have to allocate memory, and the db rea/disk write will happen sequentially. Instead I would write out to the buffered writer for every read that you make from the db, and so the operation will be closer to a concurrent one (I don't know if you're doing that or not)
This is currently on the Preferences tab which is the default. You may need to scroll down. This checkbox has been moved at least a couple times since this question was asked. Last I checked, it was in the middle column at the bottom. If you have it open on a thinner screen and there are 2 columns under Preferences, it may be near the top right. Feel free to update this post if it changes or comment and I'll update the post.
Building on the above solutions.
This will work across all project bundles and no need for generics when calling fromNib().
Swift 2
extension UIView {
public class func fromNib() -> Self {
return fromNib(nil)
}
public class func fromNib(nibName: String?) -> Self {
func fromNibHelper<T where T : UIView>(nibName: String?) -> T {
let bundle = NSBundle(forClass: T.self)
let name = nibName ?? String(T.self)
return bundle.loadNibNamed(name, owner: nil, options: nil)?.first as? T ?? T()
}
return fromNibHelper(nibName)
}
}
Swift 3
extension UIView {
public class func fromNib() -> Self {
return fromNib(nibName: nil)
}
public class func fromNib(nibName: String?) -> Self {
func fromNibHelper<T>(nibName: String?) -> T where T : UIView {
let bundle = Bundle(for: T.self)
let name = nibName ?? String(describing: T.self)
return bundle.loadNibNamed(name, owner: nil, options: nil)?.first as? T ?? T()
}
return fromNibHelper(nibName: nibName)
}
}
Can be used like this:
let someView = SomeView.fromNib()
Or like this:
let someView = SomeView.fromNib("SomeOtherNibFileName")
Unfortunately, ggplot2 does not offer a way to do this (easily) without transforming your data into long format. You can try to fight it but it will just be easier to do the data transformation. Here all the methods, including melt
from reshape2, gather
from tidyr, and pivot_longer
from tidyr: Reshaping data.frame from wide to long format
Here's a simple example using pivot_longer
:
> df <- data.frame(time = 1:5, a = 1:5, b = 3:7)
> df
time a b
1 1 1 3
2 2 2 4
3 3 3 5
4 4 4 6
5 5 5 7
> df_wide <- df %>% pivot_longer(c(a, b), names_to = "colname", values_to = "val")
> df_wide
# A tibble: 10 x 3
time colname val
<int> <chr> <int>
1 1 a 1
2 1 b 3
3 2 a 2
4 2 b 4
5 3 a 3
6 3 b 5
7 4 a 4
8 4 b 6
9 5 a 5
10 5 b 7
As you can see, pivot_longer
puts the selected column names in whatever is specified by names_to
(default "name"), and puts the long values into whatever is specified by values_to
(default "value"). If I'm ok with the default names, I can use use df %>% pivot_longer(c("a", "b"))
.
Now you can plot as normal, ex.
ggplot(df_wide, aes(x = time, y = val, color = colname)) + geom_line()
Export Particular DataBases
djimi:> mysqldump --user=root --host=localhost --port=3306 --password=test -B CCR KIT >ccr_kit_local.sql
this will export CCR and KIT databases...
Import All Exported DB to Particular Mysql Instance (You have to be where your dump file is)
djimi:> mysql --user=root --host=localhost --port=3306 --password=test < ccr_kit_local.sql
make mylist into a List<MyObject>
, is one option
In some cases, you might need business logic to be performed by a parent component. In the example below we have a child component that renders table row depending on the logic provided by the parent component:
@Component({
...
template: '<table-component [getRowColor]="getColor"></table-component>',
directives: [TableComponent]
})
export class ParentComponent {
// Pay attention on the way this function is declared. Using fat arrow (=>) declaration
// we can 'fixate' the context of `getColor` function
// so that it is bound to ParentComponent as if .bind(this) was used.
getColor = (row: Row) => {
return this.fancyColorService.getUserFavoriteColor(row);
}
}
@Component({...})
export class TableComponent{
// This will be bound to the ParentComponent.getColor.
// I found this way of declaration a bit safer and convenient than just raw Function declaration
@Input('getRowColor') getRowColor: (row: Row) => Color;
renderRow(){
....
// Notice that `getRowColor` function holds parent's context because of a fat arrow function used in the parent
const color = this.getRowColor(row);
renderRow(row, color);
}
}
So, I wanted to demonstrate 2 things here:
In your config.ini
file of eclipse eclipse\configuration\config.ini
check this three things:
osgi.framework=file\:plugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
osgi.bundles=reference\:file\:org.eclipse.equinox.simpleconfigurator_1.0.0.v20080604.jar@1\:start
org.eclipse.equinox.simpleconfigurator.configUrl=file\:org.eclipse.equinox.simpleconfigurator\\bundles.info
And check whether these jars are in place or not, the jar files depend upon your version of eclipse .
You need to use get_serving_url
from the Images API. As that page explains, you need to call create_gs_key()
first to get the key to pass to the Images API.
You must use $lastId = $this->db->insert_id();
<iframe>
The iframe element represents a nested browsing context. HTML 5 standard - "The
<iframe>
element"
Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>
's strength is that the embedded code is 'live' and can communicate with the parent document.
<embed>
Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...
The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The
<embed>
element")
Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.
The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:
svg = document.getElementById("parent_id").getSVGDocument();
From inside an embedded SVG or HTML document you can reach the parent with:
parent = window.parent.document;
For embedded HTML there is no way to get at the embedded document from the parent (that I have found).
<object>
The
<object>
element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The<object>
element")
Unless you are embedding SVG or something static you are probably best of using <iframe>
. To include SVG use <embed>
(if I remember correctly <object>
won't let you script†). Honestly I don't know why you would use <object>
unless for older browsers or flash (that I don't work with).
† As pointed out in the comments below; scripts in <object>
will run but the parent and child contexts can't communicate directly. With <embed>
you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object>
or <iframe>
where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.
Since Apache library is deprecated, for those who want to use HttpURLConncetion
, I wrote this class to send Get and Post Request with the help of this answer:
public class WebService {
static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";
static CookieManager msCookieManager = new CookieManager();
private static int responseCode;
public static String sendPost(String requestURL, String urlParameters) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
conn.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
if (urlParameters != null) {
writer.write(urlParameters);
}
writer.flush();
writer.close();
os.close();
Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
setResponseCode(conn.getResponseCode());
if (getResponseCode() == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
// HTTP GET request
public static String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", "Mozilla");
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form cookieManager and load them to connection:
*/
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
//While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
con.setRequestProperty(COOKIE ,
TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
}
/*
* https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
* Get Cookies form response header and load them to cookieManager:
*/
Map<String, List<String>> headerFields = con.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static void setResponseCode(int responseCode) {
WebService.responseCode = responseCode;
Log.i("Milad", "responseCode" + responseCode);
}
public static int getResponseCode() {
return responseCode;
}
}
I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.
log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS
Whenever you create child class object then that object has all the features of parent class. Here Super() is the facilty for accession parent.
If you write super() at that time parents's default constructor is called. same if you write super.
this keyword refers the current object same as super key word facilty for accessing parents.
The below snippet examines EAX using GDB.
(gdb) info register eax
eax 0xaa55 43605
(gdb) info register ax
ax 0xaa55 -21931
(gdb) info register ah
ah 0xaa -86
(gdb) info register al
al 0x55 85
The accepted answer didn't work for me. To fix that issue, I had to right-click on the file that was locked, select repo-browser
. This opened a popup with the files as they are on the SVN server. I then right-clicked on the locked file and selected break lock
.
When I closed the repository browser, back on explorer I could finally commit!
If you want to view all the commits that changed a file, in all the branches, use this:
git log --follow --all <filepath>
For the log folder and file stuff, go with @Bens answer.
I will comment on the creating log part, though. Imo there is no correct way. When coding loggers manually I do it the way you're doing it:
ILog logger = LogManager.GetLogger(typeof(CCController));
because it is short and concise.
That said, I do not create the logger instances inside the classes these days, I let my IoC container inject it for me.
x = "my_test"
last_char = x.split('').last
there are some syntax errors to your program heres a working code;
#include<stdio.h>
int main()
{
int a,b;
printf("enter any two number\n");
scanf("%d%d",&a,&b);
if (a%b==0){
printf("this is multiple number");
}
else if (b%a==0){
printf("this is multiple number");
}
else{
printf("this is not multiple number");
return 0;
}
}
The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.
import java.net.InetAddress;
import java.net.UnknownHostException;
String hostname = "Unknown";
try
{
InetAddress addr;
addr = InetAddress.getLocalHost();
hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
System.out.println("Hostname can not be resolved");
}
You can use the following steps:
Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this
pip freeze >> requirements.txt
else store package names in a file named requirements.txt
Step 2: Execute pip command with this file
pip install -r requirements.txt
I was facing the problem in passing string value to string parameters in Ajax. After so much googling, i have come up with a custom solution as below.
var bar = 'xyz';
var calibri = 'no$libri';
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "http://nakolesah.ru/",
data: '{ foo: \'' + bar + '\', zoo: \'' + calibri + '\'}',
success: function(msg){
alert('wow'+msg);
},
});
Here, bar and calibri are two string variables and you can pass whatever string value to respective string parameters in web method.
Since it returns tuples (and can use tons of memory), the zip(*zipped)
trick seems more clever than useful, to me.
Here's a function that will actually give you the inverse of zip.
def unzip(zipped):
"""Inverse of built-in zip function.
Args:
zipped: a list of tuples
Returns:
a tuple of lists
Example:
a = [1, 2, 3]
b = [4, 5, 6]
zipped = list(zip(a, b))
assert zipped == [(1, 4), (2, 5), (3, 6)]
unzipped = unzip(zipped)
assert unzipped == ([1, 2, 3], [4, 5, 6])
"""
unzipped = ()
if len(zipped) == 0:
return unzipped
dim = len(zipped[0])
for i in range(dim):
unzipped = unzipped + ([tup[i] for tup in zipped], )
return unzipped
Simple excel file create in mvc 4
public ActionResult results() { return File(new System.Text.UTF8Encoding().GetBytes("string data"), "application/csv", "filename.csv"); }
The Lambda function expects JSON input, therefore parsing the query string is needed. The solution is to change the query string to JSON using the Mapping Template.
I used it for C# .NET Core, so the expected input should be a JSON with "queryStringParameters" parameter.
Follow these 4 steps below to achieve that:
application/json
content-tyap:Copy the template below, which parses the query string into JSON, and paste it into the mapping template:
{
"queryStringParameters": {#foreach($key in $input.params().querystring.keySet())#if($foreach.index > 0),#end"$key":"$input.params().querystring.get($key)"#end}
}
In the API Gateway, call your Lambda function and add the following query string (for the example): param1=111¶m2=222¶m3=333
The mapping template should create the JSON output below, which is the input for your Lambda function.
{
"queryStringParameters": {"param3":"333","param1":"111","param2":"222"}
}
You're done. From this point, your Lambda function's logic can use the query string parameters.
Good luck!
You are always allowed to initialize a final
variable. The compiler makes sure that you can do it only once.
Note that calling methods on an object stored in a final
variable has nothing to do with the semantics of final
. In other words: final
is only about the reference itself, and not about the contents of the referenced object.
Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.
There is a way to do this using the system property "user.dir". The key part to understand is that getAbsoluteFile() must be called (as shown below) or else relative paths will be resolved against the default "user.dir" value.
import java.io.*;
public class FileUtils
{
public static boolean setCurrentDirectory(String directory_name)
{
boolean result = false; // Boolean indicating whether directory was set
File directory; // Desired current working directory
directory = new File(directory_name).getAbsoluteFile();
if (directory.exists() || directory.mkdirs())
{
result = (System.setProperty("user.dir", directory.getAbsolutePath()) != null);
}
return result;
}
public static PrintWriter openOutputFile(String file_name)
{
PrintWriter output = null; // File to open for writing
try
{
output = new PrintWriter(new File(file_name).getAbsoluteFile());
}
catch (Exception exception) {}
return output;
}
public static void main(String[] args) throws Exception
{
FileUtils.openOutputFile("DefaultDirectoryFile.txt");
FileUtils.setCurrentDirectory("NewCurrentDirectory");
FileUtils.openOutputFile("CurrentDirectoryFile.txt");
}
}
private Random gen = new Random();
DateTime RandomDay()
{
DateTime start = new DateTime(1995, 1, 1);
int range = (DateTime.Today - start).Days;
return start.AddDays(gen.Next(range));
}
For better performance if this will be called repeatedly, create the start
and gen
(and maybe even range
) variables outside of the function.
You can use: marshaller.setProperty("jaxb.fragment", Boolean.TRUE);
It works for me on Java 8
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
You're near :)
First, the batch (%%variable) and Windows CMD (%variable) uses different variable naming. Second, i dont figure out how do you use zip from CMD. This is from Linux users i think. Use built-in zip manipulation is not like easy on Win, and even harder with batch scripting.
But you're lucky anyway. I got (extracted to target folder) zip.exe and cygwin1.dll from the cygwin package (3mb filesize both together) and start play with it right now.
Of course, i use CMD for better/faster testing instead batch. Only remember modify the %varname to %%varname before blame me :P
for /d %d in (*) do zip -r %d %d
Explanation:
for /d ...
that matches any folder inside. Only folder ignoring files. (use for /f to filesmatch)
for /d %d in ...
the %d tells cmd wich name do you wanna assign to your variable. I put d to match widh d (directory meaning).
for /d %d in (*) ...
Very important. That suposses that I CD
to desired folder, or run from. (*)
this will mean all on THIS dir, because we use /d
the files are not processed so no need to set a pattern, even if you can get only some folders if you need. You can use absolute paths. Not sure about issues with relatives from batch.
for /d %d in (*) do zip -r ...
Do ZIP is obvious. (exec zip itself and see the help display to use your custom rules). r- is for recursive, so anyting will be added.
for /d %d in (*) do zip -r %d %d
The first %d is the zip name. You can try with myzip.zip, but if will fail because if you have 2 or more folders the second cannot gave the name of the first and will not try to overwrite without more params. So, we pass %d to both, wich is the current for iteration folder name zipped into a file with the folder name. Is not neccesary to append ".zip" to name.
Is pretty short than i expected when start to play with.
I think you are talking about ctrl + shift + F, by default it should be on "look in: entire solution" and there you go.
Update your remote if you still haven't done so:
$ git remote update
$ git branch -r
This way should cover a situation of concurrency when the function is called again while is still executing (and items need used only once):
while (list.Count > 0)
{
string Item = list[0];
list.RemoveAt(0);
// do here what you need to do with item
}
If the function get called while is still executing items will not reiterate from the first again as they get deleted as soon as they get used. Should not affect performance much for small lists.
The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.
The Panel does have outer HTML tags but does have some cool extra properties.
BackImageUrl: Gets/Sets the background image's URL for the panel
HorizontalAlign: Gets/Sets the
horizontal alignment of the parent's
contents
There is a good article at startvbnet here.
You get this error message if a Python file was closed from "the outside", i.e. not from the file object's close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that's not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
Salt is used to add an extra level of complexity to the hash, to make it harder to brute-force crack.
From an article on Sitepoint:
A hacker can still perform what's called a dictionary attack. Malicious parties may make a dictionary attack by taking, for instance, 100,000 passwords that they know people use frequently (e.g. city names, sports teams, etc.), hash them, and then compare each entry in the dictionary against each row in the database table. If the hackers find a match, bingo! They have your password. To solve this problem, however, we need only salt the hash.
To salt a hash, we simply come up with a random-looking string of text, concatenate it with the password supplied by the user, then hash both the randomly generated string and password together as one value. We then save both the hash and the salt as separate fields within the Users table.
In this scenario, not only would a hacker need to guess the password, they'd have to guess the salt as well. Adding salt to the clear text improves security: now, if a hacker tries a dictionary attack, he must hash his 100,000 entries with the salt of every user row. Although it's still possible, the chances of hacking success diminish radically.
There is no method automatically doing this in .NET, so you'll have go with the solution above.
Simply show a new window with two buttons. Add property to contain user result.
select to_char(sysdate,'DAY') from dual; It's work try it
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset
to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
As explained in Cloning a Git repo from VSTS over SSH asks a password! Unexpected
The problem may be because of public key authentication failing, so it then asks for mycompany account's password.
This would not happen if the public key authentication succeeded.
So you might check id_rsa.pub and even create a new one.
begin
for i in (select 'drop table '||table_name||' cascade constraints' tbl from user_tables)
loop
execute immediate i.tbl;
end loop;
end;
Actually sometimes when you are updating one table from another table's data, I think one of the common issues that cause this error, is when you use your table abbreviations incorrectly or when they are not needed. The correct statement is below:
Update Table1
Set SomeField = t2.SomeFieldValue
From Table1 t1
Inner Join Table2 as t2
On t1.ID = t2.ID
Notice that SomeField
column from Table1 doesn't have the t1
qualifier as t1.SomeField
but is just SomeField
.
If one tries to update it by specifying t1.SomeField
the statement will return the multi-part error that you have noticed.
i was facing lot of issues when i was trying other solution...... After lot of R&D now i got solution
create custom_spinner.xml in layout folder and paste this code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorGray">
<TextView
android:id="@+id/tv_spinnervalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/colorWhite"
android:gravity="center"
android:layout_alignParentLeft="true"
android:textSize="@dimen/_18dp"
android:layout_marginTop="@dimen/_3dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="@drawable/men_icon"/>
</RelativeLayout>
in your activity
Spinner spinner =(Spinner)view.findViewById(R.id.sp_colorpalates);
String[] years = {"1996","1997","1998","1998"};
spinner.setAdapter(new SpinnerAdapter(this, R.layout.custom_spinner, years));
create a new class of adapter
public class SpinnerAdapter extends ArrayAdapter<String> {
private String[] objects;
public SpinnerAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.objects=objects;
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
private View getCustomView(final int position, View convertView, ViewGroup parent) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_spinner, parent, false);
final TextView label=(TextView)row.findViewById(R.id.tv_spinnervalue);
label.setText(objects[position]);
return row;
}
}
A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.
One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:
http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf
Here is the code:
class HTTPFilestoreHandler(SimpleHTTPRequestHandler):
def __init__(self, fs_path, *args):
self.fs_path = fs_path # Filestore path
SimpleHTTPRequestHandler.__init__(self, *args)
def send_head(self):
# Overwrite SimpleHTTPRequestHandler.send_head to force download name
path = self.path
get_index = (path == '/')
self.log_message("path: %s" % path)
if '/download_as/' in path:
p_parts = path.split('/download_as/')
assert len(p_parts) == 2, 'Bad download link:' + path
path, download_as = p_parts
path = self.translate_path(path )
f = None
if os.path.isdir(path):
if not self.path.endswith('/'):
# Redirect browser - doing basically what Apache does
self.send_response(301)
self.send_header("Location", self.path + "/")
self.end_headers()
return None
else:
return self.list_directory(path)
ctype = self.guess_type(path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found")
return None
self.send_response(200)
self.send_header("Content-type", ctype)
fs = os.fstat(f.fileno())
self.send_header("Expires", '0')
self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
self.send_header("Content-Transfer-Encoding", 'binary')
if download_as:
self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
self.send_header("Content-Length", str(fs[6]))
self.send_header("Connection", 'close')
self.end_headers()
return f
class HTTPFilestoreServer:
def __init__(self, fs_path, server_address):
def handler(*args):
newHandler = HTTPFilestoreHandler(fs_path, *args)
newHandler.protocol_version = "HTTP/1.0"
self.server = BaseHTTPServer.HTTPServer(server_address, handler)
def serve_forever(self, *args):
self.server.serve_forever(*args)
def start_server(fs_path, ip_address, port):
server_address = (ip_address, port)
httpd = HTTPFilestoreServer(fs_path, server_address)
sa = httpd.server.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
go to the directory of .Net framework and register their the respective dll with Regsvr32.exe white space dll path.
NOTE: Pure Swift 3 (Xcode 8) example:
Please try out the following sample code. It is the simple example of dataTask
function of URLSession
.
func simpleDataRequest() {
//Get the url from url string
let url:URL = URL(string: "YOUR URL STRING")!
//Get the session instance
let session = URLSession.shared
//Create Mutable url request
var request = URLRequest(url: url as URL)
//Set the http method type
request.httpMethod = "POST"
//Set the cache policy
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
//Post parameter
let paramString = "key=value"
//Set the post param as the request body
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response , error == nil else {
//Oops! Error occured.
print("error")
return
}
//Get the raw response string
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//Print the response
print(dataString!)
}
//resume the task
task.resume()
}
This seems to work easily.
Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
Dim MyDoc As New mshtml.HTMLDocument
Dim DocElements As mshtml.IHTMLElementCollection = Nothing
Dim LoginForm As mshtml.HTMLFormElement = Nothing
ASPComplete = 0
WB.Navigate(VitecLoginURI)
BrowserLoop()
MyDoc = WB.Document.DomDocument
DocElements = MyDoc.getElementsByTagName("input")
For Each i As mshtml.IHTMLElement In DocElements
Select Case i.name
Case "seLogin$UserName"
i.value = UserID
Case "seLogin$Password"
i.value = Pass
Case Else
Exit Select
End Select
frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
Next i
'Old Method for Clicking submit
'WB.Document.Forms("form1").InvokeMember("submit")
'Better Method to click submit
LoginForm = MyDoc.forms.item("form1")
LoginForm.item("seLogin$LoginButton").click()
ASPComplete = 0
BrowserLoop()
MyDoc= WB.Document.DomDocument
DocElements = MyDoc.getElementsByTagName("input")
For Each j As mshtml.IHTMLElement In DocElements
frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf
Next j
frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
Return 1
End Function
I just wanted to share a combined snippet for hiding the scrollbar that I use when developing. It is a collection of several snippets found on the Internet that works for me:
.container {
overflow-x: scroll; /* For horiz. scroll, otherwise overflow-y: scroll; */
-ms-overflow-style: none;
overflow: -moz-scrollbars-none;
scrollbar-width: none;
}
.container::-webkit-scrollbar {
display: none; /* Safari and Chrome */
}
From http://www.gitguys.com/topics/adding-and-removing-remote-branches/
After someone deletes a branch from a remote repository, git will not automatically delete the local repository branches when a user does a git pull or git fetch. However, if the user would like to have all tracking branches removed from their local repository that have been deleted in a remote repository, they can type:
git remote prune origin
As a note, the -p param from git fetch -p
actually means "prune".
Either way you chose, the non-existing remote branches will be deleted from your local repository.
This is a good overview:
http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html
or run this code:
32 bit process:
NSLog(@"Primitive sizes:");
NSLog(@"The size of a char is: %d.", sizeof(char));
NSLog(@"The size of short is: %d.", sizeof(short));
NSLog(@"The size of int is: %d.", sizeof(int));
NSLog(@"The size of long is: %d.", sizeof(long));
NSLog(@"The size of long long is: %d.", sizeof(long long));
NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
NSLog(@"The size of a float is: %d.", sizeof(float));
NSLog(@"The size of a double is %d.", sizeof(double));
NSLog(@"Ranges:");
NSLog(@"CHAR_MIN: %c", CHAR_MIN);
NSLog(@"CHAR_MAX: %c", CHAR_MAX);
NSLog(@"SHRT_MIN: %hi", SHRT_MIN); // signed short int
NSLog(@"SHRT_MAX: %hi", SHRT_MAX);
NSLog(@"INT_MIN: %i", INT_MIN);
NSLog(@"INT_MAX: %i", INT_MAX);
NSLog(@"LONG_MIN: %li", LONG_MIN); // signed long int
NSLog(@"LONG_MAX: %li", LONG_MAX);
NSLog(@"ULONG_MAX: %lu", ULONG_MAX); // unsigned long int
NSLog(@"LLONG_MIN: %lli", LLONG_MIN); // signed long long int
NSLog(@"LLONG_MAX: %lli", LLONG_MAX);
NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX); // unsigned long long int
When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:
Primitive sizes:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 4.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 4.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -2147483648
LONG_MAX: 2147483647
ULONG_MAX: 4294967295
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
64 bit process:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
Here is a nice way to display the information that you want:
SELECT B.table_catalog as 'Database_Name',
B.table_name as 'Table_Name',
stuff((select ', ' + A.column_name
from INFORMATION_SCHEMA.COLUMNS A
where A.Table_name = B.Table_Name
FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)')
, 1, 2, '') as 'Columns'
FROM INFORMATION_SCHEMA.COLUMNS B
WHERE B.TABLE_NAME like '%%'
AND B.COLUMN_NAME like '%%'
GROUP BY B.Table_Catalog, B.Table_Name
Order by 1 asc
Add anything between either '%%' in the main select to narrow down what tables and/or column names you want.
In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric
geom_segment(data=tmpp,
aes(x=start_pos,
y=lib.complexity,
xend=end_pos,
yend=lib.complexity)
)
# to
geom_segment(data=tmpp,
aes(x=as.numeric(start_pos),
y=as.numeric(lib.complexity),
xend=as.numeric(end_pos),
yend=as.numeric(lib.complexity))
)