Don't forget also that the path for the file is on the actual oracle server machine and not any local development machine that might be calling your stored procedure. This is probably very obvious but something that should be remembered.
Old question, but thought I'd add this to help out,
#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif
My requirements included:
My solution in the end was to use SimpleJson(https://github.com/facebook-csharp-sdk/simple-json).
Although you can install it via a nuget package, I included just that single SimpleJson.cs file (with the MIT license) in my project and referenced it.
I hope this helps someone.
You need to add
#container
{
display:inline-block;
position:relative;
background:rgb(255,100,0);
margin:0px;
width:40%;
height:100px;
margin-right:-4px;
}
because whenever you write display:inline-block
it takes an additional margin-right:4px
. So, you need to remove it.
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
I wrote a Tester
class which can test the performance:
public class Tester
{
public static void main(String[] args)
{
String text = "";
int loopCount = 10000000;
long startTime, endTime, duration1, duration2;
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.equals("");
}
endTime = System.nanoTime();
duration1 = endTime - startTime;
System.out.println(".equals(\"\") duration " +": \t" + duration1);
startTime = System.nanoTime();
for (int i = 0; i < loopCount; i++) {
text.isEmpty();
}
endTime = System.nanoTime();
duration2 = endTime - startTime;
System.out.println(".isEmpty() duration "+": \t\t" + duration2);
System.out.println("isEmpty() to equals(\"\") ratio: " + ((float)duration2 / (float)duration1));
}
}
I found that using .isEmpty()
took around half the time of .equals("")
.
Your assignments are all nested within your conditional if blocks which means that there is potential for them to never be assigned.
At the top of your class, initialise them to 0 or some other value
You can use Perl style regular expressions as well. A digit is just \d
then.
grep -Po "\\d+" filename
-P Interpret PATTERNS as Perl-compatible regular expressions (PCREs).
-o Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.
From the JDK source:
static <T> Function<T, T> identity() {
return t -> t;
}
So, no, as long as it is syntactically correct.
On CentOS 6.6/Grep 2.6.3, I have to use it like this:
grep "term" -Hnir --include \*.php --exclude-dir "*excluded_dir*"
Notice the lack of equal signs "=" (otherwise --include
, --exclude
, include-dir
and --exclude-dir
are ignored)
Late answer, but hopefully worthwhile: The Poor Man's T-SQL Formatter is an open-source (free) T-SQL formatter with complete T-SQL batch/script support (any DDL, any DML), SSMS Plugin, command-line bulk formatter, and other options.
It's available for immediate/online use at http://poorsql.com, and just today graduated to "version 1.0" (it was in beta version for a few months), having just acquired support for MERGE
statements, OUTPUT
clauses, and other finicky stuff.
The SSMS Add-in allows you to set your own hotkey (default is Ctrl-K, Ctrl-F, to match Visual Studio), and formats the entire script or just the code you have selected/highlighted, if any. Output formatting is customizable.
In SSMS 2008 it combines nicely with the built-in intelli-sense, effectively providing more-or-less the same base functionality as Red Gate's SQL Prompt (SQL Prompt does, of course, have extra stuff, like snippets, quick object scripting, etc).
Feedback/feature requests are more than welcome, please give it a whirl if you get the chance!
Disclosure: This is probably obvious already but I wrote this library/tool/site, so this answer is also shameless self-promotion :)
It turns out the best solution for me here was to just reformat the drive. Once reformatted all these problems were no longer problems.
Simple Solution worked 100% for me
Put the class outside App_Code Folder
http://vishaljoshi.blogspot.in/2009/07/appcode-folder-doesnt-work-with-web.html
OK, there are couple of ways to show all files in a particular commit...
To reduce the info and show only names of the files which committed, you simply can add --name-only
or --name-status
flag..., these flags just show you the file names which are different from previous commits as you want...
So you can do git diff
followed by --name-only
, with two commit hashes after <sha0> <sha1>
, something like below:
git diff --name-only 5f12f15 kag9f02
I also create the below image to show all steps to go through in these situation:
from pyspark.sql.functions import udf
from pyspark.sql.types import *
func_name = udf(
lambda val: val, # do sth to val
StringType()
)
df.withColumn('new_col', func_name(df.old_col))
import * as saveAsFunctions from 'file-saver';
..........
.......
let saveAs;
beforeEach(() => {
saveAs = jasmine.createSpy('saveAs');
})
it('should generate the excel on sample request details page', () => {
spyOn(saveAsFunctions, 'saveAs').and.callFake(saveAs);
expect(saveAsFunctions.saveAs).toHaveBeenCalled();
})
This worked for me.
I had the same problem, Android Studio just could not identify the android-sdk folder. All I did was to uninstall and reinstall android studio, and this time it actually identified the folder. Hope it also works out for you.
SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29';
it helps , you can convert the values as DATE
before comparing.
This error may be triggered by insufficient memory on RDP server.
After few tries with this error, RDP managed to get a connection to the server and I was able to stop a bogus service consuming too much memory. This can be done also with sysinternals or sc.
If the DC is Win2k3 SP2 or above, you can use something like:
(&(objectCategory=user)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com))
to get the nested group membership.
Source: https://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches
This worked for me:
Do
$ git status
And check if you have Unmerged paths
# Unmerged paths:
# (use "git reset HEAD <file>..." to unstage)
# (use "git add <file>..." to mark resolution)
#
# both modified: app/assets/images/logo.png
# both modified: app/models/laundry.rb
Fix them with git add
to each of them and try git stash
again.
git add app/assets/images/logo.png
I got the top answer working (can't reply yet) after one small edit
This did not work for me:
FEATURE('authinfo','hash /etc/mail/auth/client-info')dnl
The first single quote for each string should be changed to a backtick (`) like this:
FEATURE(`authinfo',`hash /etc/mail/auth/client-info')dnl
After the change I run:
sudo sendmailconfig
And I'm in business :)
I recently ran into the same problem but the issue wasn't related to tabs and spaces but an odd Unicode character that appeared invisible to the eye in my IDE. Eventually, I isolated the problem and typed out the line exactly as it was and checked the git
diff:
If you are able to isolate the line before the reported line and type it out again, you might find that it solves your problem. Won't tell you why it happened in the first place, but it at least gets rid of the issue.
Source Link
Demo Link
The following code will show Multiple Markers with InfoWindow. You can Uncomment code to show Info on Hover as well
var map;
var InforObj = [];
var centerCords = {
lat: -25.344,
lng: 131.036
};
var markersOnMap = [{
placeName: "Australia (Uluru)",
LatLng: [{
lat: -25.344,
lng: 131.036
}]
},
{
placeName: "Australia (Melbourne)",
LatLng: [{
lat: -37.852086,
lng: 504.985963
}]
},
{
placeName: "Australia (Canberra)",
LatLng: [{
lat: -35.299085,
lng: 509.109615
}]
},
{
placeName: "Australia (Gold Coast)",
LatLng: [{
lat: -28.013044,
lng: 513.425586
}]
},
{
placeName: "Australia (Perth)",
LatLng: [{
lat: -31.951994,
lng: 475.858081
}]
}
];
window.onload = function () {
initMap();
};
function addMarkerInfo() {
for (var i = 0; i < markersOnMap.length; i++) {
var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
'</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';
const marker = new google.maps.Marker({
position: markersOnMap[i].LatLng[0],
map: map
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 200
});
marker.addListener('click', function () {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
// marker.addListener('mouseover', function () {
// closeOtherInfo();
// infowindow.open(marker.get('map'), marker);
// InforObj[0] = infowindow;
// });
// marker.addListener('mouseout', function () {
// closeOtherInfo();
// infowindow.close();
// InforObj[0] = infowindow;
// });
}
}
function closeOtherInfo() {
if (InforObj.length > 0) {
InforObj[0].set("marker", null);
InforObj[0].close();
InforObj.length = 0;
}
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: centerCords
});
addMarkerInfo();
}
That would be the modulo operator, which produces the remainder of the division of two numbers.
Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"
There are a couple of options:
Just after initialising DataTables, remove the sorting classes on the TD element in the TBODY.
Disable the sorting classes using http://datatables.net/ref#bSortClasses . Problem with this is that it will disable the sort classes for user sort requests - which might or might not be what you want.
Have your server output the table in your required sort order, and don't apply a default sort on the table (aaSorting:[]
).
[a-zA-Z0-9] will only match ASCII characters, it won't match
String target = new String("A" + "\u00ea" + "\u00f1" +
"\u00fc" + "C");
If you also want to match unicode characters:
String pat = "^[\\p{L}0-9]*$";
Simple way - you can specify .* in the beginning because find matches the whole path.
$ find . -regextype egrep -regex '.*[a-f0-9\-]{36}\.jpg$'
find version
$ find --version
find (GNU findutils) 4.6.0
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Eric B. Decker, James Youngman, and Kevin Dalley.
Features enabled: D_TYPE O_NOFOLLOW(enabled) LEAF_OPTIMISATION
FTS(FTS_CWDFD) CBO(level=2)
do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.
Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).
If you need to make a comparison between a class and a known type, for example:
class Example{};
...
Example eg = Example();
You can use this comparison line:
bool isType = string( typeid(eg).name() ).find("Example") != string::npos;
which checks the typeid
name contains the string type (the typeid name has other mangled data, so its best to do a s1.find(s2)
instead of ==
).
Install Oracle's MySql.Data
NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
A common trick is to check like this:
trim(TextBox1.Value & vbnullstring) = vbnullstring
this will work for spaces, empty strings, and genuine null values
To get the all selected Items in a CheckedListBox try this:
In this case ths value is a String but it's run with other type of Object:
for (int i = 0; i < myCheckedListBox.Items.Count; i++)
{
if (myCheckedListBox.GetItemChecked(i) == true)
{
MessageBox.Show("This is the value of ceckhed Item " + myCheckedListBox.Items[i].ToString());
}
}
I found this way of using ajax which helped me as it was better in use as not having complex json syntaxes
//fifth
function GetAjaxDataPromise(url, postData) {
debugger;
var promise = $.post(url, postData, function (promise, status) {
});
return promise;
};
$(function () {
$("#btnGet5").click(function () {
debugger;
var promises = GetAjaxDataPromise('@Url.Action("AjaxMethod", "Home")', { EmpId: $("#txtId").val(), EmpName: $("#txtName").val(), EmpSalary: $("#txtSalary").val() });
promises.done(function (response) {
debugger;
alert("Hello: " + response.EmpName + " Your Employee Id Is: " + response.EmpId + "And Your Salary Is: " + response.EmpSalary);
});
});
});
This method comes with jquery promise the best part was on controller we can received data by using separate parameters or just by using a model class.
[HttpPost]
public JsonResult AjaxMethod(PersonModel personModel)
{
PersonModel person = new PersonModel
{
EmpId = personModel.EmpId,
EmpName = personModel.EmpName,
EmpSalary = personModel.EmpSalary
};
return Json(person);
}
or
[HttpPost]
public JsonResult AjaxMethod(string empId, string empName, string empSalary)
{
PersonModel person = new PersonModel
{
EmpId = empId,
EmpName = empName,
EmpSalary = empSalary
};
return Json(person);
}
It works for both of the cases. SO you must try out this way. Got the reference from Using Ajax With Asp.Net MVC
There are few more ways of using Ajax explained there other than this one which you must try.
Remove a file with .dat extension in workspace/.metadata/.plugins/org.eclipse.wst.jsdt.core/ and then close eand open eclipse, maybe you cannot close eclipse, force it, with pkill -f eclipse if you are on linux or similar.
This solution avoid to import all of existents projects.
Since it is your files in your app bundle, I think you can use pathForResource:ofType:
to get the full pathname of your file.
Here is an example:
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name"
ofType:@"the_file_extension"];
If you want to redirect previous location or last request then you have to include user_agent
library:
$this->load->library('user_agent');
and then use at last in a function that you are using:
redirect($this->agent->referrer());
its working for me.
A constructor in Java doesn't actually "build" the object, it is used to initialize fields.
Imagine that your abstract class has fields x and y, and that you always want them to be initialized in a certain way, no matter what actual concrete subclass is eventually created. So you create a constructor and initialize these fields.
Now, if you have two different subclasses of your abstract class, when you instantiate them their constructors will be called, and then the parent constructor will be called and the fields will be initialized.
If you don't do anything, the default constructor of the parent will be called. However, you can use the super keyword to invoke specific constructor on the parent class.
I found a workaround for this via this link. In a nutshell, you have to:
Put this command inside the above file(Replace the path for executable if necessary):
#!/bin/sh
"C:\Program Files\Sublime Text 2\sublime_text.exe" $1 &
Place that subl file inside the adequate command directory according to your OS and Sublime Text version (If you have doubts, check the above link comments section). In my case, I'm using Sublime Text 3 with Windows 10 64bit so I placed it in:
C:\Program Files (x86)\Git\usr\bin
Now, in order for you to open the desired file, in git bash use (within file folder)
subl filename
Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10
Add these extensions :
extension CGRect{
init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
self.init(x:x,y:y,width:width,height:height)
}
}
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension CGPoint{
init(_ x:CGFloat,_ y:CGFloat) {
self.init(x:x,y:y)
}
}
Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize
These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3
The "Pythonic" way to check if a string is empty is:
import random
variable = random.choice(l)
if variable:
# got a non-empty string
else:
# got an empty string
After you granted the permissions to the specified user you have to do this at filtering:
First step:
Second step:
Now you will be able to display the tables after you changed the default load Alter session to the desire schema (using a Trigger after LOG ON).
Here are two examples of how to generate graphs in separate windows (frames), and, an example of how to generate graphs and save them into separate graphics files.
Okay, first the on-screen example. Notice that we use a separate instance of plt.figure(), for each graph, with plt.plot(). At the end, we have to call plt.show() to put it all on the screen.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show()
Another way to do this, is to use plt.show(block=False) inside the loop:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.show( block=False )
Now, let's generate the graphs and instead, write them each to a file. Here we replace plt.show(), with plt.savefig( filename ). The difference from the previous example is that we don't have to account for ''blocking'' at each graph. Note also, that we number the file names. Here we use %03d so that we can conveniently have them in number order afterwards.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace( 0,10 )
for n in range(3):
y = np.sin( x+n )
plt.figure()
plt.plot( x, y )
plt.savefig('myfilename%03d.png'%(n))
I'd just add to the answers the "why?".
.
is standard member access operator that has a higher precedence than *
pointer operator.
When you are trying to access a struct's internals and you wrote it as *foo.bar
then the compiler would think to want a 'bar' element of 'foo' (which is an address in memory) and obviously that mere address does not have any members.
Thus you need to ask the compiler to first dereference whith (*foo)
and then access the member element: (*foo).bar
, which is a bit clumsy to write so the good folks have come up with a shorthand version: foo->bar
which is sort of member access by pointer operator.
I had a similar problem where CREATE FULLTEXT
timed out after 30 seconds:
Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:
Also, I did not have to restart mysql workbench for this to work.
You can use wait
:
some_command &
P1=$!
other_command &
P2=$!
wait $P1 $P2
It assigns the background program PIDs to variables ($!
is the last launched process' PID), then the wait
command waits for them. It is nice because if you kill the script, it kills the processes too!
Technically a Tier can be a kind of minimum environment required for the code to run.
E.g. hypothetically a 3-tier app can be running on
1 physical machine with 3 virtual machines with no OS.
(That was a 3-(hardware)tier app)
1 physical machine with 3 virtual machines with 3 different/same OSes
(That was a 3-(OS)tier app)
1 physical machine with 1 virtual machine with 1 OS but 3 AppServers
(That was a 3-(AppServer)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServer but 3 DBMS
(That was a 3-(DBMS)tier app)
1 physical machine with 1 virtual machine with 1 OS with 1 AppServers and 1 DBMS but 3 Excel workbooks.
(That was a 3-(AppServer)tier app)
Excel workbook is the minimum required environment for VBA code to run.
Those 3 workbooks can sit on a single physical computer or multiple.
I have noticed that in practice people mean "OS Tier" when they say "Tier" in the app description context.
That is if an app runs on 3 separate OS then its a 3-Tier app.
So a pedantically correct way describing an app would be
"1-to-3-Tier capable, running on 2 Tiers" app.
:)
Layers are just types of code in respect to the functional separation of duties withing the app (e.g. Presentation, Data , Security etc.)
You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools
These will check both WSDL validity and Basic Profile 1.1 compliance.
in this situation, you would grab the element by its id using getElementById
and then just use .src
var youtubeimgsrc = document.getElementById("youtubeimg").src;
Building on Lucas's answer above, this is an overload that takes a controller name as parameter, similar to ActionLink. Use this overload when your image links to an Action in a different controller.
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, string controllerName, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
Generally people pull the official image of Ubuntu/CentOS but they don't realize that these images are minimal and doesn't have any thing on the top of that.
For Ubuntu, this image is built from official rootfs tarballs provided by Canonical. Given that it is a minimal install of Ubuntu, this image only includes the C, C.UTF-8, and POSIX locales by default.
One can install net-tools (includes ifconfig, netstat), ip-utils(includes ping) andy other likes curl etc on container and can create image from container or can write Dockerfile that will install these tool while creating image.
Below is Dockerfile example, while creating image from this it will include these tools:
FROM vkitpro/ubuntu16.04
RUN apt-get update -y \
&& apt-get upgrade -y \
&& apt-get install iputils-ping -y \
&& apt-get install net-tools -y \
CMD bash
or launch container from base image and install these utilities on container and then commit to image. docker commit -m "any descriptive message" container_id image_name:lattest
That image will have all thing installed.
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creationI am using JsonProperty attributes when serializing but ignoring them when deserializing using this ContractResolver
:
public class IgnoreJsonPropertyContractResolver: DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
foreach (var p in properties) { p.PropertyName = p.UnderlyingName; }
return properties;
}
}
The ContractResolver
just sets every property back to the class property name (simplified from Shimmy's solution). Usage:
var airplane= JsonConvert.DeserializeObject<Airplane>(json,
new JsonSerializerSettings { ContractResolver = new IgnoreJsonPropertyContractResolver() });
In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.
Syntax problem on your arrays
$array1 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
);
$array2 = array(
'a' => 'value1',
'b' => 'value2',
'c' => 'value3',
);
$diff = array_diff($array1, $array2);
var_dump($diff);
No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.
The Bundle
is a container for all the information you want to save. You use the put* functions to insert data into it. Here's a short list (there are more) of put functions you can use to store data in the Bundle
.
putString
putBoolean
putByte
putChar
putFloat
putLong
putShort
putParcelable (used for objects but they must implement Parcelable)
In your onCreate
function, this Bundle
is handed back to the program. The best way to check if the application is being reloaded, or started for the first time is:
if (savedInstanceState != null) {
// Then the application is being reloaded
}
To get the data back out, use the get* functions just like the put* functions. The data is stored as a name-value pair. This is like a hashmap. You provide a key and the value, then when you want the value back, you give the key and the function gets the value. Here's a short example.
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("message", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String message = savedInstanceState.getString("message");
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
Your saved message will be toasted to the screen. Hope this helps.
If you're doing for Canada remember that not all letters are valid
These letters are invalid: D, F, I, O, Q, or U And the letters W and Z are not used as the first letter. Also some people use an optional space after the 3rd character.
Here is a regular expression for Canadian postal code:
new RegExp(/^[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz]\s?[0-9][abceghjklmnprstvwxyz][0-9]$/i)
The last i makes it case insensitive.
is called a generic type. You can instantiate an object Pool like this:
PoolFactory<Integer> pool = new Pool<Integer>();
The generic parameter can only be a reference type. So you can't use primitive types like int or double or char or other primitive types.
In Excel 2013 simply select multiple sheets and do a "Save As" and select PDF as the file type. The multiple pages will open in PDF when you click save.
mosquitto.org is very active (at the time of this posting). This is a nice smoke test for a MQTT subscriber linux device:
mosquitto_sub -h test.mosquitto.org -t "#" -v
The "#" is a wildcard for topics and returns all messages (topics): the server had a lot of traffic, so it returned a 'firehose' of messages.
If your MQTT device publishes a topic of irisys/V4D-19230005/
to the test MQTT broker , then you could filter the messages:
mosquitto_sub -h test.mosquitto.org -t "irisys/V4D-19230005/#" -v
Options:
If you only want to skip CSRF protection for one or more controller actions (instead of the entire controller), try this
skip_before_action :verify_authenticity_token, only [:webhook, :index, :create]
Where [:webhook, :index, :create]
will skip the check for those 3 actions, but you can change to whichever you want to skip
I was looking for a solution to this problem myself with no luck, so I had to roll my own which I would like to share here with you. (Please excuse my bad English) (It's a little crazy to answer another Czech guy in English :-) )
The first thing I tried was to use a good old PopupWindow
. It's quite easy - one only has to listen to the OnMarkerClickListener
and then show a custom PopupWindow
above the marker. Some other guys here on StackOverflow suggested this solution and it actually looks quite good at first glance. But the problem with this solution shows up when you start to move the map around. You have to move the PopupWindow
somehow yourself which is possible (by listening to some onTouch events) but IMHO you can't make it look good enough, especially on some slow devices. If you do it the simple way it "jumps" around from one spot to another. You could also use some animations to polish those jumps but this way the PopupWindow
will always be "a step behind" where it should be on the map which I just don't like.
At this point, I was thinking about some other solution. I realized that I actually don't really need that much freedom - to show my custom views with all the possibilities that come with it (like animated progress bars etc.). I think there is a good reason why even the google engineers don't do it this way in the Google Maps app. All I need is a button or two on the InfoWindow that will show a pressed state and trigger some actions when clicked. So I came up with another solution which splits up into two parts:
First part:
The first part is to be able to catch the clicks on the buttons to trigger some action. My idea is as follows:
MapFragment
(or MapView
) inside a custom ViewGroup (mine is called MapWrapperLayout)MapWrapperLayout
's dispatchTouchEvent and (if the InfoWindow is currently shown) first route the MotionEvents to the previously created InfoWindow. If it doesn't consume the MotionEvents (like because you didn't click on any clickable area inside InfoWindow etc.) then (and only then) let the events go down to the MapWrapperLayout's superclass so it will eventually be delivered to the map.Here is the MapWrapperLayout's source code:
package com.circlegate.tt.cg.an.lib.map;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.Marker;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;
public class MapWrapperLayout extends RelativeLayout {
/**
* Reference to a GoogleMap object
*/
private GoogleMap map;
/**
* Vertical offset in pixels between the bottom edge of our InfoWindow
* and the marker position (by default it's bottom edge too).
* It's a good idea to use custom markers and also the InfoWindow frame,
* because we probably can't rely on the sizes of the default marker and frame.
*/
private int bottomOffsetPixels;
/**
* A currently selected marker
*/
private Marker marker;
/**
* Our custom view which is returned from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow
*/
private View infoWindow;
public MapWrapperLayout(Context context) {
super(context);
}
public MapWrapperLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MapWrapperLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Must be called before we can route the touch events
*/
public void init(GoogleMap map, int bottomOffsetPixels) {
this.map = map;
this.bottomOffsetPixels = bottomOffsetPixels;
}
/**
* Best to be called from either the InfoWindowAdapter.getInfoContents
* or InfoWindowAdapter.getInfoWindow.
*/
public void setMarkerWithInfoWindow(Marker marker, View infoWindow) {
this.marker = marker;
this.infoWindow = infoWindow;
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
boolean ret = false;
// Make sure that the infoWindow is shown and we have all the needed references
if (marker != null && marker.isInfoWindowShown() && map != null && infoWindow != null) {
// Get a marker position on the screen
Point point = map.getProjection().toScreenLocation(marker.getPosition());
// Make a copy of the MotionEvent and adjust it's location
// so it is relative to the infoWindow left top corner
MotionEvent copyEv = MotionEvent.obtain(ev);
copyEv.offsetLocation(
-point.x + (infoWindow.getWidth() / 2),
-point.y + infoWindow.getHeight() + bottomOffsetPixels);
// Dispatch the adjusted MotionEvent to the infoWindow
ret = infoWindow.dispatchTouchEvent(copyEv);
}
// If the infoWindow consumed the touch event, then just return true.
// Otherwise pass this event to the super class and return it's result
return ret || super.dispatchTouchEvent(ev);
}
}
All this will make the views inside the InfoView "live" again - the OnClickListeners will start triggering etc.
Second part: The remaining problem is, that obviously, you can't see any UI changes of your InfoWindow on screen. To do that you have to manually call Marker.showInfoWindow. Now, if you perform some permanent change in your InfoWindow (like changing the label of your button to something else), this is good enough.
But showing a button pressed state or something of that nature is more complicated. The first problem is, that (at least) I wasn't able to make the InfoWindow show normal button's pressed state. Even if I pressed the button for a long time, it just remained unpressed on the screen. I believe this is something that is handled by the map framework itself which probably makes sure not to show any transient state in the info windows. But I could be wrong, I didn't try to find this out.
What I did is another nasty hack - I attached an OnTouchListener
to the button and manually switched it's background when the button was pressed or released to two custom drawables - one with a button in a normal state and the other one in a pressed state. This is not very nice, but it works :). Now I was able to see the button switching between normal to pressed states on the screen.
There is still one last glitch - if you click the button too fast, it doesn't show the pressed state - it just remains in its normal state (although the click itself is fired so the button "works"). At least this is how it shows up on my Galaxy Nexus. So the last thing I did is that I delayed the button in it's pressed state a little. This is also quite ugly and I'm not sure how would it work on some older, slow devices but I suspect that even the map framework itself does something like this. You can try it yourself - when you click the whole InfoWindow, it remains in a pressed state a little longer, then normal buttons do (again - at least on my phone). And this is actually how it works even on the original Google Maps app.
Anyway, I wrote myself a custom class which handles the buttons state changes and all the other things I mentioned, so here is the code:
package com.circlegate.tt.cg.an.lib.map;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import com.google.android.gms.maps.model.Marker;
public abstract class OnInfoWindowElemTouchListener implements OnTouchListener {
private final View view;
private final Drawable bgDrawableNormal;
private final Drawable bgDrawablePressed;
private final Handler handler = new Handler();
private Marker marker;
private boolean pressed = false;
public OnInfoWindowElemTouchListener(View view, Drawable bgDrawableNormal, Drawable bgDrawablePressed) {
this.view = view;
this.bgDrawableNormal = bgDrawableNormal;
this.bgDrawablePressed = bgDrawablePressed;
}
public void setMarker(Marker marker) {
this.marker = marker;
}
@Override
public boolean onTouch(View vv, MotionEvent event) {
if (0 <= event.getX() && event.getX() <= view.getWidth() &&
0 <= event.getY() && event.getY() <= view.getHeight())
{
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN: startPress(); break;
// We need to delay releasing of the view a little so it shows the pressed state on the screen
case MotionEvent.ACTION_UP: handler.postDelayed(confirmClickRunnable, 150); break;
case MotionEvent.ACTION_CANCEL: endPress(); break;
default: break;
}
}
else {
// If the touch goes outside of the view's area
// (like when moving finger out of the pressed button)
// just release the press
endPress();
}
return false;
}
private void startPress() {
if (!pressed) {
pressed = true;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawablePressed);
if (marker != null)
marker.showInfoWindow();
}
}
private boolean endPress() {
if (pressed) {
this.pressed = false;
handler.removeCallbacks(confirmClickRunnable);
view.setBackground(bgDrawableNormal);
if (marker != null)
marker.showInfoWindow();
return true;
}
else
return false;
}
private final Runnable confirmClickRunnable = new Runnable() {
public void run() {
if (endPress()) {
onClickConfirmed(view, marker);
}
}
};
/**
* This is called after a successful click
*/
protected abstract void onClickConfirmed(View v, Marker marker);
}
Here is a custom InfoWindow layout file that I used:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="10dp" >
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:text="Title" />
<TextView
android:id="@+id/snippet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="snippet" />
</LinearLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Test activity layout file (MapFragment
being inside the MapWrapperLayout
):
<com.circlegate.tt.cg.an.lib.map.MapWrapperLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map_relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</com.circlegate.tt.cg.an.lib.map.MapWrapperLayout>
And finally source code of a test activity, which glues all this together:
package com.circlegate.testapp;
import com.circlegate.tt.cg.an.lib.map.MapWrapperLayout;
import com.circlegate.tt.cg.an.lib.map.OnInfoWindowElemTouchListener;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ViewGroup infoWindow;
private TextView infoTitle;
private TextView infoSnippet;
private Button infoButton;
private OnInfoWindowElemTouchListener infoButtonListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.map);
final MapWrapperLayout mapWrapperLayout = (MapWrapperLayout)findViewById(R.id.map_relative_layout);
final GoogleMap map = mapFragment.getMap();
// MapWrapperLayout initialization
// 39 - default marker height
// 20 - offset between the default InfoWindow bottom edge and it's content bottom edge
mapWrapperLayout.init(map, getPixelsFromDp(this, 39 + 20));
// We want to reuse the info window for all the markers,
// so let's create only one class member instance
this.infoWindow = (ViewGroup)getLayoutInflater().inflate(R.layout.info_window, null);
this.infoTitle = (TextView)infoWindow.findViewById(R.id.title);
this.infoSnippet = (TextView)infoWindow.findViewById(R.id.snippet);
this.infoButton = (Button)infoWindow.findViewById(R.id.button);
// Setting custom OnTouchListener which deals with the pressed state
// so it shows up
this.infoButtonListener = new OnInfoWindowElemTouchListener(infoButton,
getResources().getDrawable(R.drawable.btn_default_normal_holo_light),
getResources().getDrawable(R.drawable.btn_default_pressed_holo_light))
{
@Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Toast.makeText(MainActivity.this, marker.getTitle() + "'s button clicked!", Toast.LENGTH_SHORT).show();
}
};
this.infoButton.setOnTouchListener(infoButtonListener);
map.setInfoWindowAdapter(new InfoWindowAdapter() {
@Override
public View getInfoWindow(Marker marker) {
return null;
}
@Override
public View getInfoContents(Marker marker) {
// Setting up the infoWindow with current's marker info
infoTitle.setText(marker.getTitle());
infoSnippet.setText(marker.getSnippet());
infoButtonListener.setMarker(marker);
// We must call this to set the current marker and infoWindow references
// to the MapWrapperLayout
mapWrapperLayout.setMarkerWithInfoWindow(marker, infoWindow);
return infoWindow;
}
});
// Let's add a couple of markers
map.addMarker(new MarkerOptions()
.title("Prague")
.snippet("Czech Republic")
.position(new LatLng(50.08, 14.43)));
map.addMarker(new MarkerOptions()
.title("Paris")
.snippet("France")
.position(new LatLng(48.86,2.33)));
map.addMarker(new MarkerOptions()
.title("London")
.snippet("United Kingdom")
.position(new LatLng(51.51,-0.1)));
}
public static int getPixelsFromDp(Context context, float dp) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int)(dp * scale + 0.5f);
}
}
That's it. So far I only tested this on my Galaxy Nexus (4.2.1) and Nexus 7 (also 4.2.1), I will try it on some Gingerbread phone when I have a chance. A limitation I found so far is that you can't drag the map from where is your button on the screen and move the map around. It could probably be overcome somehow but for now, I can live with that.
I know this is an ugly hack but I just didn't find anything better and I need this design pattern so badly that this would really be a reason to go back to the map v1 framework (which btw. I would really really like to avoid for a new app with fragments etc.). I just don't understand why Google doesn't offer developers some official way to have a button on InfoWindows. It's such a common design pattern, moreover this pattern is used even in the official Google Maps app :). I understand the reasons why they can't just make your views "live" in the InfoWindows - this would probably kill performance when moving and scrolling map around. But there should be some way how to achieve this effect without using views.
Print all args without the filename:
for i in range(1, len(sys.argv)):
print(sys.argv[i])
Easiest
eval(myvar)(parameter1, parameter2)
You don't have a function "pointer". You have a function "name".
While this works well, you will have a large number of folks telling you it's "insecure" or a "security risk".
ES6 supports now class
& static
keywords like a charm :
class Foo {
constructor() {}
talk() {
console.log("i am not static");
}
static saying() {
console.log(this.speech);
}
static get speech() {
return "i am static method";
}
}
you can also use jquery for this
var phoneNumber = 8882070980;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(phoneNumber)) {
if(phoneNumber.length==10){
var validate = true;
} else {
alert('Please put 10 digit mobile number');
var validate = false;
}
}
else {
alert('Not a valid number');
var validate = false;
}
if(validate){
//number is equal to 10 digit or number is not string
enter code here...
}
Since a datetime without a specified time segment will have a value of date 00:00:00.000
, if you want to be sure you get all the dates in your range, you must either supply the time for your ending date or increase your ending date and use <
.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date < '2011/02/28'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
DO NOT use the following, as it could return some records from 2011/02/28 if their times are 00:00:00.000.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/28'
Lolz this is much better
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/);
return pattern.test(emailAddress);
};
SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
SELECT MAX(p2.PAYM_DATE)
FROM user_payments as p2
WHERE p2.USER_ID = p.USER_ID
)
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
Image Layer: Repositories are often referred to as images or container images, but actually they are made up of one or more layers. Image layers in a repository are connected together in a parent-child relationship. Each image layer represents changes between itself and the parent layer.
The docker building pattern uses inheritance. It means the version i
depends on version i-1
. So, we must delete the version i+1
to be able to delete version i
. This is a simple dependency.
If you wanna delete all images except the last one (the most updated) and the first (base) then we can export the last (the most updated one) using docker save
command as below.
docker save -o <output_file> <your_image-id> | gzip <output_file>.tgz
Then, now, delete all the images using image-id as below.
docker rm -f <image-id i> | docker rm -f <image i-1> | docker rm -f <image-id i-2> ... <docker rm -f <image-id i-k> # where i-k = 1
Now, load your saved tgz image as below.
gzip -c <output_file.tgz> | docker load
see the image-id of your loaded image using docker ps -q. It doesn't have tag and name. You can simply update tag and name as done below.
docker tag <image_id> group_name/name:tag
My suggestion for google maps api v3 would be(don't think it can be done more effeciently):
gmap : {
fitBounds: function(bounds, mapId)
{
//incoming: bounds - bounds object/array; mapid - map id if it was initialized in global variable before "var maps = [];"
if (bounds==null) return false;
maps[mapId].fitBounds(bounds);
}
}
In the result u will fit all points in bounds in your map window.
Example works perfectly and u freely can check it here www.zemelapis.lt
I was having a similar problem. I only had the following starter web package.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
But it is not enough. You need to add a parent too to get other required dependencies.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
How to drop rows of Pandas DataFrame whose value in a certain column is NaN
This is an old question which has been beaten to death but I do believe there is some more useful information to be surfaced on this thread. Read on if you're looking for the answer to any of the following questions:
DataFrame.dropna
: Usage, and ExamplesIt's already been said that df.dropna
is the canonical method to drop NaNs from DataFrames, but there's nothing like a few visual cues to help along the way.
# Setup
df = pd.DataFrame({
'A': [np.nan, 2, 3, 4],
'B': [np.nan, np.nan, 2, 3],
'C': [np.nan]*3 + [3]})
df
A B C
0 NaN NaN NaN
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Below is a detail of the most important arguments and how they work, arranged in an FAQ format.
This is where the how=...
argument comes in handy. It can be one of
'any'
(default) - drops rows if at least one column has NaN'all'
- drops rows only if all of its columns have NaNs<!_ ->
# Removes all but the last row since there are no NaNs
df.dropna()
A B C
3 4.0 3.0 3.0
# Removes the first row only
df.dropna(how='all')
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Note
If you just want to see which rows are null (IOW, if you want a boolean mask of rows), useisna
:df.isna() A B C 0 True True True 1 False True True 2 False False True 3 False False False df.isna().any(axis=1) 0 True 1 True 2 True 3 False dtype: bool
To get the inversion of this result, use
notna
instead.
This is a use case for the subset=[...]
argument.
Specify a list of columns (or indexes with axis=1
) to tells pandas you only want to look at these columns (or rows with axis=1
) when dropping rows (or columns with axis=1
.
# Drop all rows with NaNs in A
df.dropna(subset=['A'])
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
# Drop all rows with NaNs in A OR B
df.dropna(subset=['A', 'B'])
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
This is a use case for the thresh=...
argument. Specify the minimum number of NON-NULL values as an integer.
df.dropna(thresh=1)
A B C
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
df.dropna(thresh=2)
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
df.dropna(thresh=3)
A B C
3 4.0 3.0 3.0
The thing to note here is you need to specify how many NON-NULL values you want to keep, rather than how many NULL values you want to drop. This is a pain point for new users.
Luckily the fix is easy: if you have a count of NULL values, simply subtract it from the column size to get the correct thresh argument for the function.
required_min_null_values_to_drop = 2 # drop rows with at least 2 NaN
df.dropna(thresh=df.shape[1] - required_min_null_values_to_drop + 1)
A B C
2 3.0 2.0 NaN
3 4.0 3.0 3.0
Use the axis=...
argument, it can be axis=0
or axis=1
.
Tells the function whether you want to drop rows (axis=0
) or drop columns (axis=1
).
df.dropna()
A B C
3 4.0 3.0 3.0
# All columns have rows, so the result is empty.
df.dropna(axis=1)
Empty DataFrame
Columns: []
Index: [0, 1, 2, 3]
# Here's a different example requiring the column to have all NaN rows
# to be dropped. In this case no columns satisfy the condition.
df.dropna(axis=1, how='all')
A B C
0 NaN NaN NaN
1 2.0 NaN NaN
2 3.0 2.0 NaN
3 4.0 3.0 3.0
# Here's a different example requiring a column to have at least 2 NON-NULL
# values. Column C has less than 2 NON-NULL values, so it should be dropped.
df.dropna(axis=1, thresh=2)
A B
0 NaN NaN
1 2.0 NaN
2 3.0 2.0
3 4.0 3.0
dropna
, like most other functions in the pandas API returns a new DataFrame (a copy of the original with changes) as the result, so you should assign it back if you want to see changes.
df.dropna(...) # wrong
df.dropna(..., inplace=True) # right, but not recommended
df = df.dropna(...) # right
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html
DataFrame.dropna( self, axis=0, how='any', thresh=None, subset=None, inplace=False)
simple
COPY README.md package.json gulpfile.js __BUILD_NUMBER ./
from the doc
If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
If you find your nested fragment not being removed or being duplicated (eg. on Activity restart, on screen rotate) try changing:
transaction.add(R.id.placeholder, newFragment);
to
transaction.replace(R.id.placeholder, newFragment);
If above doesn't help, try:
Fragment f = getChildFragmentManager().findFragmentById(R.id.placeholder);
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
if (f == null) {
Log.d(TAG, "onCreateView: fragment doesn't exist");
newFragment= new MyFragmentType();
transaction.add(R.id.placeholder, newFragment);
} else {
Log.d(TAG, "onCreateView: fragment already exists");
transaction.replace(R.id.placeholder, f);
}
transaction.commit();
Learnt here
The quoting rules are painful. I think you want:
SELECT nextval('foo."SQ_ID"');
to prevent case-folding of SQ_ID
.
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
Assuming you have people is List of object
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Now you need two steps :
1)
people =removeDuplicate(people);
2)
Map<String, String> phoneBook=people.stream()
.collect(toMap(Person::getName, Person::getAddress));
Here is method to remove duplicate
public static List removeDuplicate(Collection<Person> list) {
if(list ==null || list.isEmpty()){
return null;
}
Object removedDuplicateList =
list.stream()
.distinct()
.collect(Collectors.toList());
return (List) removedDuplicateList;
}
Adding full example here
package com.example.khan.vaquar;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class RemovedDuplicate {
public static void main(String[] args) {
Person vaquar = new Person(1, "Vaquar", "Khan");
Person zidan = new Person(2, "Zidan", "Khan");
Person zerina = new Person(3, "Zerina", "Khan");
// Add some random persons
Collection<Person> duplicateList = Arrays.asList(vaquar, zidan, zerina, vaquar, zidan, vaquar);
//
System.out.println("Before removed duplicate list" + duplicateList);
//
Collection<Person> nonDuplicateList = removeDuplicate(duplicateList);
//
System.out.println("");
System.out.println("After removed duplicate list" + nonDuplicateList);
;
// 1) solution Working code
Map<Object, Object> k = nonDuplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 1 using method_______________________________________________");
System.out.println("k" + k);
System.out.println("_____________________________________________________________________");
// 2) solution using inline distinct()
Map<Object, Object> k1 = duplicateList.stream().distinct()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("Result 2 using inline_______________________________________________");
System.out.println("k1" + k1);
System.out.println("_____________________________________________________________________");
//breacking code
System.out.println("");
System.out.println("Throwing exception _______________________________________________");
Map<Object, Object> k2 = duplicateList.stream()
.collect(Collectors.toMap(s1 -> s1.getId(), s1 -> s1));
System.out.println("");
System.out.println("k2" + k2);
System.out.println("_____________________________________________________________________");
}
public static List removeDuplicate(Collection<Person> list) {
if (list == null || list.isEmpty()) {
return null;
}
Object removedDuplicateList = list.stream().distinct().collect(Collectors.toList());
return (List) removedDuplicateList;
}
}
// Model class
class Person {
public Person(Integer id, String fname, String lname) {
super();
this.id = id;
this.fname = fname;
this.lname = lname;
}
private Integer id;
private String fname;
private String lname;
// Getters and Setters
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
@Override
public String toString() {
return "Person [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
Results :
Before removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=1, fname=Vaquar, lname=Khan]]
After removed duplicate list[Person [id=1, fname=Vaquar, lname=Khan], Person [id=2, fname=Zidan, lname=Khan], Person [id=3, fname=Zerina, lname=Khan]]
Result 1 using method_______________________________________________
k{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Result 2 using inline_______________________________________________
k1{1=Person [id=1, fname=Vaquar, lname=Khan], 2=Person [id=2, fname=Zidan, lname=Khan], 3=Person [id=3, fname=Zerina, lname=Khan]}
_____________________________________________________________________
Throwing exception _______________________________________________
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Person [id=1, fname=Vaquar, lname=Khan]
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1253)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.khan.vaquar.RemovedDuplicate.main(RemovedDuplicate.java:48)
public static LocalTime time() {
LocalTime ldt = java.time.LocalTime.now();
ldt = ldt.truncatedTo(ChronoUnit.MINUTES);
System.out.println(ldt);
return ldt;
}
This works for me
As your project is a console project you can pass the path to the text files that you want to read via the string[] args
static void Main(string[] args)
{
}
Within Main you can check if arguments are passed
if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}
Extract an argument
string fileToRead = args[0];
Nearly all languages support the concept of argument passing and follow similar patterns to C#.
For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx
No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.
:only-child
The :only-child
is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1)
probably would.
:nth-child
The :nth-child
selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:
p:nth-child( n + 8 ){
/* add styles to make it pretty */
}
Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.
W3 CSS3 Spec on pseudo-classes
EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:
:empty
and :not
This styles elements that have no children. Not that useful on its own, but when paired with the :not
selector, you can style only the elements that have children:
div:not(:empty) {
/* We know it has stuff in it! */
}
You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.
public List<Object> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new {pro.ProjectName,pro.ProjectId};
return query.ToList<Object>();
}
}
My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.
@GetMapping("/downloadfile/{productId}/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable(value = "productId") String productId,
@PathVariable String fileName, HttpServletRequest request) {
// Load file as Resource
Resource resource;
String fileBasePath = "C:\\Users\\v_fzhang\\mobileid\\src\\main\\resources\\data\\Filesdown\\" + productId
+ "\\";
Path path = Paths.get(fileBasePath + fileName);
try {
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
// Try to determine file's content type
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
System.out.println("Could not determine file type.");
}
// Fallback to the default content type if type could not be determined
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
To test it, use postman
docker build -t name1:tag1 -t name2:tag2 -f Dockerfile.ui .
Better would have been generate url like
app.dev/backend?type=surveys&id=2
and then use
var type=$location.search().type;
var id=$location.search().id;
and inject $location in controller.
In swift 4.2 I used following code to show and hide code using NSNotification
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let keyboardheight = keyboardSize.height
print(keyboardheight)
}
}
Allow Apache Through the Firewall
Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:
sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp
And reload the firewall:
sudo firewall-cmd --reload
select2
has the placeholder
parameter. Use that one
$("#state").select2({
placeholder: "Choose a Country"
});
I had the same problem and builded a .htaccess
file to fix this issue with a few more improvements. You can use it as it is, just download it from Github Gist and change the filename "public/index.php" to "public/app.php" and see how it works! :)
I have craeted a little script for read directory and write a console name new file (example: 'name.txt' ) and text into file.
const readline = require('readline');
const fs = require('fs');
const pathFile = fs.readdirSync('.');
const file = readline.createInterface({
input: process.stdin,
output: process.stdout
});
file.question('Insert name of your file? ', (f) => {
console.log('File is: ',f.toString().trim());
try{
file.question('Insert text of your file? ', (d) => {
console.log('Text is: ',d.toString().trim());
try {
if(f != ''){
if (fs.existsSync(f)) {
//file exists
console.log('file exist');
return file.close();
}else{
//save file
fs.writeFile(f, d, (err) => {
if (err) throw err;
console.log('The file has been saved!');
file.close();
});
}
}else{
//file empty
console.log('Not file is created!');
console.log(pathFile);
file.close();
}
} catch(err) {
console.error(err);
file.close();
}
});
}catch(err){
console.log(err);
file.close();
}
});
Just in case this helps anyone else:
If you're going to be adding the TimeOut
directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!
Jersey needs to be unpacked jars.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<requiresUnpack>
<dependency>
<groupId>com.myapp</groupId>
<artifactId>rest-api</artifactId>
</dependency>
</requiresUnpack>
</configuration>
</plugin>
</plugins>
</build>
Had the same problem, and it was not solved before i read the post from DZDomi. It suddenly occurred to be that there is a setting in the Google Developer Console that you need to enable. In the "In app purchases" section, there's a line for your product and to the far right there's a status for it. It should be ACTIVE!
On Selenium >= 3.41 (C#) the rigth syntax is:
webDriver = webDriver.SwitchTo().Frame(webDriver.FindElement(By.Name("icontent")));
The theoretical advantage of *.ico files is that they are containers than can hold more than one icon. You could for instance store an image with alpha channel and a 16 colour version for legacy systems, or you could add 32x32 and 48x48 icons (which would show up when e.g. dragging a link to Windows explorer).
This good idea, however, tends to clash with browser implementations.
Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:
uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)
GetHashCode()
is used to help support using the object as a key for hash tables. (A similar thing exists in Java etc). The goal is for every object to return a distinct hash code, but this often can't be absolutely guaranteed. It is required though that two logically equal objects return the same hash code.
A typical hash table implementation starts with the hashCode value, takes a modulus (thus constraining the value within a range) and uses it as an index to an array of "buckets".
Most debugger consoles support displaying objects directly. Just use
console.log(obj);
Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.
One-to-one: Use a foreign key to the referenced table:
student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
# "link back" if you need
You must also put a unique constraint on the foreign key column (addess.student_id
) to prevent multiple rows in the child table (address
) from relating to the same row in the referenced table (student
).
One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:
teachers: teacher_id, first_name, last_name # the "one" side
classes: class_id, class_name, teacher_id # the "many" side
Many-to-many: Use a junction table (example):
student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id # the junction table
Example queries:
-- Getting all students for a class:
SELECT s.student_id, last_name
FROM student_classes sc
INNER JOIN students s ON s.student_id = sc.student_id
WHERE sc.class_id = X
-- Getting all classes for a student:
SELECT c.class_id, name
FROM student_classes sc
INNER JOIN classes c ON c.class_id = sc.class_id
WHERE sc.student_id = Y
Got this working using LayerDrawable:
fun getResizedDrawable(drawable: Drawable, scale: Float) =
LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, (drawable.intrinsicWidth * scale).toInt(), (drawable.intrinsicHeight * scale).toInt()) }
fun getResizedDrawable(drawable: Drawable, scalex: Float, scaleY: Float) =
LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, (drawable.intrinsicWidth * scalex).toInt(), (drawable.intrinsicHeight * scaleY).toInt()) }
fun getResizedDrawableUsingSpecificSize(drawable: Drawable, newWidth: Int, newHeight: Int) =
LayerDrawable(arrayOf(drawable)).also { it.setLayerSize(0, newWidth, newHeight) }
Example:
val drawable = AppCompatResources.getDrawable(this, android.R.drawable.sym_def_app_icon)!!
val resizedDrawable = getResizedDrawable(drawable, 3f)
textView.setCompoundDrawablesWithIntrinsicBounds(resizedDrawable, null, null, null)
imageView.setImageDrawable(resizedDrawable)
Playing devil's advocate a little bit:
You should check the DjangoCon 2008 Keynote, delivered by Cal Henderson, titled "Why I hate Django" where he pretty much goes over everything Django is missing that you might want to do in a high traffic website. At the end of the day you have to take this all with an open mind because it is perfectly possible to write Django apps that scale, but I thought it was a good presentation and relevant to your question.
write this:
#siteInfo{text-align:center}
p, input{display:inline-block}
Make sure you have following configuration in your pom.xml
file.
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
Here's the obligatory dplyr
answer in case somebody wants to do this with the pipe.
test %>%
select(sort(names(.)))
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
From the documentation:
We can add to a list in many ways:
assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
//equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]
def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]
list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]
list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']
You can also do:
def myNewList = myList << "fifth"
This is not your answer and this is an alternate way to process the form submission
$('.signinform').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'index.php/user/signin', // target element(s) to be updated with server response
dataType:'json',
success : function(response){ console.log(response); alert(response)}
});
});
While installing Netbeans itself, you will get an option which servers needs to be installed and integrated with Netbeans. First screen itself will show.
Another option is to reinstall Netbeans by closing all the open projects.
Or you can try to access the columns directly by name:
while(dr.Read())
{
string col1 = (string)dr["Value1"];
string col2 = (string)dr["Value2"];
string col3 = (string)dr["Value3"];
}
Load it into Reflector and see what it references?
for example:
This is a sample I used for my unit test. I created a list of class object. Then I used forloop to add 'X' number of objects that I am expecting from the service. This way you can add/initialize a List for any given size.
public void TestMethod1()
{
var expected = new List<DotaViewer.Interface.DotaHero>();
for (int i = 0; i < 22; i++)//You add empty initialization here
{
var temp = new DotaViewer.Interface.DotaHero();
expected.Add(temp);
}
var nw = new DotaHeroCsvService();
var items = nw.GetHero();
CollectionAssert.AreEqual(expected,items);
}
Hope I was of help to you guys.
You have problem with like this: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
Ans: $ sudo service mysql start
As a general rule, I'd always advocate explicitly calling the Dispose method for any class that offers it, either by calling the method directly or wrapping in a "using" block.
Most often, classes that implement IDisposible do so because they wrap some unmanaged resource that needs to be freed. While these classes should have finalizers that act as a safeguard, calling Dispose will help free that memory earlier and with lower overhead.
In the case of the Form object, as the link fro Kyra noted, the Close method is documented to invoke Dispose on your behalf so you need not do so explicitly. However, to me, that has always felt like relying on an implementaion detail. I prefer to always call both Close and Dispose for classes that implement them, to guard against implementation changes/errors and for the sake of being clear. A properly implemented Dispose method should be safe to invoke multiple times.
DotPeek from JetBrains provides quick and easy way to see msil(anycpu), x86, x64
You can use .offset()
to get the offset compared to the document
element and then use the scrollTop
property of the window
element to find how far down the page the user has scrolled:
var scrollTop = $(window).scrollTop(),
elementOffset = $('#my-element').offset().top,
distance = (elementOffset - scrollTop);
The distance
variable now holds the distance from the top of the #my-element
element and the top-fold.
Here is a demo: http://jsfiddle.net/Rxs2m/
Note that negative values mean that the element is above the top-fold.
On Windows, Subversion stores the auth data in %APPDATA%\Subversion\auth
. The passwords however are stored encrypted, not in plaintext.
You can decrypt those, but only if you log in to Windows as the same user for which the auth data was saved.
Someone even wrote a tool to decrypt those. Never tried the tool myself so I don't know how well it works, but you might want to try it anyway:
http://www.leapbeyond.com/ric/TSvnPD/
Update: In TortoiseSVN 1.9 and later, you can do it without any additional tools:
Settings Dialog
-> Saved Data
, then click the "Clear...
" button right of the text "Authentication Data
". A new dialog pops up, showing all stored authentication data where you can chose which one(s) to clear. Instead of clearing, hold down the Shift
and Ctrl
button, and then double click
on the list. A new column is shown in the dialog which shows the password in clear.
This answer is more usefull when you are bringing data from a DB, make modifications and then persist the changes.
<select ng-options="opt.id as opt.name for opt in users" ng-model="selectedUser"></select>
Check the example here:
I don't see the need for Indirect, especially for conditional formatting.
The simplest way to self-reference a cell, row or column is to refer to it normally, e.g., "=A1" in cell A1, and make the reference partly or completely relative. For example, in a conditional formatting formula for checking whether there's a value in the first column of various cells' rows, enter the following with A1 highlighted and copy as necessary. The conditional formatting will always refer to column A for the row of each cell:
= $A1 <> ""
How about this (in you don't want an one liner) ?
for row in df.collect():
d = row.asDict()
s = "%d\t%s\t%s\n" % (d["int_column"], d["string_column"], d["string_column"])
f.write(s)
f is a opened file descriptor. Also the separator is a TAB char, but it's easy to change to whatever you want.
I faced same issue in eclipse neon simple maven java project
But I add below details inside pom.xml file
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
After right click on project > maven > update project (checked force update)
Its resolve me to display error on project
Hope it's will helpful
Thansk
Isn't it just: System.out.println(Array.length);
? Because this is what it seems like you are looking for.
eval
takes a string as its argument, and evaluates it as if you'd typed that string on a command line. (If you pass several arguments, they are first joined with spaces between them.)
${$n}
is a syntax error in bash. Inside the braces, you can only have a variable name, with some possible prefix and suffixes, but you can't have arbitrary bash syntax and in particular you can't use variable expansion. There is a way of saying “the value of the variable whose name is in this variable”, though:
echo ${!n}
one
$(…)
runs the command specified inside the parentheses in a subshell (i.e. in a separate process that inherits all settings such as variable values from the current shell), and gathers its output. So echo $($n)
runs $n
as a shell command, and displays its output. Since $n
evaluates to 1
, $($n)
attempts to run the command 1
, which does not exist.
eval echo \${$n}
runs the parameters passed to eval
. After expansion, the parameters are echo
and ${1}
. So eval echo \${$n}
runs the command echo ${1}
.
Note that most of the time, you must use double quotes around variable substitutions and command substitutions (i.e. anytime there's a $
): "$foo", "$(foo)"
. Always put double quotes around variable and command substitutions, unless you know you need to leave them off. Without the double quotes, the shell performs field splitting (i.e. it splits value of the variable or the output from the command into separate words) and then treats each word as a wildcard pattern. For example:
$ ls
file1 file2 otherfile
$ set -- 'f* *'
$ echo "$1"
f* *
$ echo $1
file1 file2 file1 file2 otherfile
$ n=1
$ eval echo \${$n}
file1 file2 file1 file2 otherfile
$eval echo \"\${$n}\"
f* *
$ echo "${!n}"
f* *
eval
is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR}
syntax. eval
is still useful when you need to construct a longer command containing operators, reserved words, etc.
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
The basic difference between
Blockquote
asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.
Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.
In addition to Samaursa's excelent answer, you can use the evolve
extension's prune
as a safe and recoverable version of strip
that will allow you to go back in case you do anything wrong.
I have these alias on my .hgrc
:
# Prunes all draft changesets on the current repository
reset-tree = prune -r "outgoing() and not obsolete()"
# *STRIPS* all draft changesets on current repository. This deletes history.
force-reset-tree = strip 'roots(outgoing())'
Note that prune
also has --keep
, just like strip
, to keep the working directory intact allowing you to recommit the files.
What worked for me is moving my project as it was on the desktop (C:\Users\lachezar.l\Desktop\MyFolder) to (C:\0\MyFolder) which as you can see uses shorter path and reducing it solved the problem.
See the MDN section on Promises. In particular, look at the return type of then().
To log in, the user-agent has to submit a request to the server and wait to receive a response. Since making your application totally stop execution during a request round-trip usually makes for a bad user experience, practically every JS function that logs you in (or performs any other form of server interaction) will use a Promise, or something very much like it, to deliver results asynchronously.
Now, also notice that return
statements are always evaluated in the context of the function they appear in. So when you wrote:
let AuthUser = data => {
return google
.login(data.username, data.password)
.then( token => {
return token;
});
};
the statement return token;
meant that the anonymous function being passed into then()
should return the token, not that the AuthUser
function should. What AuthUser
returns is the result of calling google.login(username, password).then(callback);
, which happens to be a Promise.
Ultimately your callback token => { return token; }
does nothing; instead, your input to then()
needs to be a function that actually handles the token in some way.
In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.
git rebase -i origin/master
Then, your commits will appear:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments
Select the commit you want to reword and save.
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments
Now, you have the opportunity to add header and body, where the first line will be the header.
Create perpetuum mobile
Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.
You can apply dirname repeatedly to climb higher: dirname(dirname(file))
. This can only go as far as the root package, however. If this is a problem, use os.path.abspath
: dirname(dirname(abspath(file)))
.
I spent about an hour looking for a more robust javascript option, and did not find one. It just so happens that in the past few days I've been fiddling with hammer.js (Hammer.js is a library that lets you manipulate all sorts of touch events easily) and mostly failing at what I was trying to do.
With that caveat, and understanding I am by no means a javascript expert, this is a solution I came up with that basically leverages hammer.js to capture the pinch-zoom and double-tap events and then log and discard them.
Make sure you include hammer.js in your page and then try sticking this javascript in the head somewhere:
< script type = "text/javascript" src="http://hammerjs.github.io/dist/hammer.min.js"> < /script >_x000D_
< script type = "text/javascript" >_x000D_
_x000D_
// SPORK - block pinch-zoom to force use of tooltip zoom_x000D_
$(document).ready(function() {_x000D_
_x000D_
// the element you want to attach to, probably a wrapper for the page_x000D_
var myElement = document.getElementById('yourwrapperelement');_x000D_
// create a new hammer object, setting "touchAction" ensures the user can still scroll/pan_x000D_
var hammertime = new Hammer(myElement, {_x000D_
prevent_default: false,_x000D_
touchAction: "pan"_x000D_
});_x000D_
_x000D_
// pinch is not enabled by default in hammer_x000D_
hammertime.get('pinch').set({_x000D_
enable: true_x000D_
});_x000D_
_x000D_
// name the events you want to capture, then call some function if you want and most importantly, add the preventDefault to block the normal pinch action_x000D_
hammertime.on('pinch pinchend pinchstart doubletap', function(e) {_x000D_
console.log('captured event:', e.type);_x000D_
e.preventDefault();_x000D_
})_x000D_
});_x000D_
</script>
_x000D_
As @Astariul said, path to the file might cause this bug.
In addition, any parent directory which contains non-ASCII character, for example Chinese, will cause this.
In that case, you should rename you parent directory
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
Try this method. It should work when field when you want to store image is of type byte
.
First it creates byte[]
for image. Then it saves it to the DB using IDataParameter
of type binary
.
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
public static void PerisitImage(string path, IDbConnection connection)
{
using (var command = connection.CreateCommand ())
{
Image img = Image.FromFile (path);
MemoryStream tmpStream = new MemoryStream();
img.Save (tmpStream, ImageFormat.Png); // change to other format
tmpStream.Seek (0, SeekOrigin.Begin);
byte[] imgBytes = new byte[MAX_IMG_SIZE];
tmpStream.Read (imgBytes, 0, MAX_IMG_SIZE);
command.CommandText = "INSERT INTO images(payload) VALUES (:payload)";
IDataParameter par = command.CreateParameter();
par.ParameterName = "payload";
par.DbType = DbType.Binary;
par.Value = imgBytes;
command.Parameters.Add(par);
command.ExecuteNonQuery ();
}
}
Also the corresponding API should be enabled for the given project
https://console.developers.google.com/apis/library?project=projectnamehere
you can use DTO pattern create class TraineeDTO without any anotation hiberbnate and you can use jackson mapper to convert Trainee to TraineeDTO and bingo the error message disapeare :)
HTML
<div id="replaceMe">i need to be replaced</div>
<div id="iamReplacement">i am replacement</div>
JavaScript
jQuery('#replaceMe').replaceWith(jQuery('#iamReplacement'));
body {
background: url(images/image_name.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Here is a good solution to get your image to cover the full area of the web app perfectly
In current versions of Mac Catalina
go to packages tab --> Settings View ---> Install Packages/Themes ---> +Install button --> add "platformio-ide-terminal"
control ~ to get the terminal
I just had the same situation (was having a hard time to address the OP's build error after adding a 3rd party framework) and it seems like a bug in Xcode
(mine is 8.3.2 (8E2002)
).
The problem was that a folder name in path to the framework contained spaces. In this case, Xcode incorrectly escaped them with backslashes like this in Build Settings
->
Framework Search Paths
:
$(PROJECT_DIR)/Folder\ with\ spaces/Lib
To fix this, just manually edit the entry to remove those backslashes and enclose the whole string in quotes like this:
"$(PROJECT_DIR)/Folder with spaces/Lib"
While working with the orientationchange
event, I needed a timeout to get the correct dimensions of the elements in the page, but matchMedia worked fine. My final code:
var matchMedia = window.msMatchMedia || window.MozMatchMedia || window.WebkitMatchMedia || window.matchMedia;
if (typeof(matchMedia) !== 'undefined') {
// use matchMedia function to detect orientationchange
window.matchMedia('(orientation: portrait)').addListener(function() {
// your code ...
});
} else {
// use orientationchange event with timeout (fires to early)
$(window).on('orientationchange', function() {
window.setTimeout(function() {
// your code ...
}, 300)
});
}
When the JVM
tries to run your application, it calls your main method statically; something like this:
LinkedList.main();
That means there is no instance of your LinkedList
class. In order to call your toString()
method, you can create a new instance of your LinkedList
class.
So the body of your main
method should be like this:
public static void main(String[] args){
// creating an instance of LinkedList class
LinkedList ll = new LinkedList();
// adding some data to the list
ll.insertFront(1);
ll.insertFront(2);
ll.insertFront(3);
ll.insertBack(4);
System.out.println(ll.toString());
}
It is used to find the how many rows contain data in a worksheet that contains data in the column "A". The full usage is
lastRowIndex = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
Where ws
is a Worksheet object. In the questions example it was implied that the statement was inside a With
block
With ws
lastRowIndex = .Cells(.Rows.Count, "A").End(xlUp).row
End With
ws.Rows.Count
returns the total count of rows in the worksheet (1048576 in Excel 2010)..Cells(.Rows.Count, "A")
returns the bottom most cell in column "A" in the worksheetThen there is the End
method. The documentation is ambiguous as to what it does.
Returns a Range object that represents the cell at the end of the region that contains the source range
Particularly it doesn't define what a "region" is. My understanding is a region is a contiguous range of non-empty cells. So the expected usage is to start from a cell in a region and find the last cell in that region in that direction from the original cell. However there are multiple exceptions for when you don't use it like that:
rng.cells(1,1)
. So Range.End
is not a trivial function.
.row
returns the row index of that cell.As I said in the comments, a <div>
element does not have a value
attribute. Although (very) bad, it can be accessed as:
console.log(document.getElementById('demo').getAttribute);
I suggest using HTML5 data-*
attributes rather. Something like this:
<div id="demo" data-myValue="1">...</div>
in which case you could access it using:
element.getAttribute('data-myValue');
//Or using jQuery:
$('#demo').data('myValue');
I solved it with converting it back to number using JavaScript's Number()
function
var x = 2.2873424;
x = Number(x.toFixed(2));
hm.
not really satisfied with the pure bash options. why not use perl to get what you want. Directly parse the $* array, and auto-name your options.
simple helper script:
#!/usr/bin/perl
use Getopt::Long;
my $optstring = shift;
my @opts = split(m#,#, $optstring);
my %opt;
GetOptions(\%opt, @opts);
print "set -- " . join(' ', map("'$_'", @ARGV)) . ";";
my $xx;
my $key;
foreach $key (keys(%opt))
{
print "export $key='$opt{$key}'; ";
}
then you can use in your script as a one liner, for example:
#!/bin/bash
eval `getopts.pl reuse:s,long_opt:s,hello $*`;
echo "HELLO: $hello"
echo "LONG_OPT: $long_opt"
echo "REUSE: $reuse"
echo $*
/tmp/script.sh hello --reuse me --long_opt whatever_you_want_except_spaces --hello 1 2 3
HELLO: 1 LONG_OPT: whatever_you_want_except spaces REUSE: me
1 2 3
Only caveat here is spaces don't work. But it avoids bash's rather complicated looping syntax, works with long args, auto-names them as variables and automatically resizes $*, so will work 99% of the time.
Use the queryset object update
method:
MyModel.objects.filter(pk=some_value).update(field1='some value')
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
In MSVC, you can use the CLR override
keyword even if you're not compiling for CLR.
In g++, there's no direct way of enforcing that in all cases; other people have given good answers on how to catch signature differences using -Woverloaded-virtual
. In a future version, someone might add syntax like __attribute__ ((override))
or the equivalent using the C++0x syntax.
Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.
Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?
Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.
There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)
just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.
var delayInMilliseconds = 500; // half a second
setTimeout(function() {
var iframe = document.getElementsByTagName('iframe')[0];
iframe.style.background = 'white';
iframe.contentWindow.document.body.style.backgroundColor = 'white';
}, delayInMilliseconds);
I hope this helps!
First create the dump. Added the --no-create-info --no-create-db
flags if table2
already exists:
mysqldump -u user1 -p database1 table1 > dump.sql
Then enter user1
password. Then:
sed -e 's/`table1`/`table2`/' dump.sql
mysql -u user2 -p database2 < dump.sql
Then enter user2
password.
Same as @helmors answer but the approach is more secure as passwords aren't exposed in raw text to the console (reverse-i-search, password sniffers, etc). Other approach is fine if it's executed from a script file with appropriate restrictions placed on it's permissions.
The fleqn
option in the document class will apply left aligning setting in all equations of the document. You can instead use \begin{flalign}
. This will align only the desired equations.
You can use the 'ours' merge strategy:
$ git checkout staging
$ git merge -s ours email # Merge branches, but use our (=staging) branch head
$ git checkout email
$ git merge staging
EDIT 2020-07-30:
I thought a bit more about this question and possible solutions. If you absolutely require the merge parents in the correct order, need perform this action with a single command line invocation, and don't mind running plumbing commands, you can do the following:
$ git checkout A
$ git merge --ff-only $(git commit-tree -m "Throw away branch 'A'" -p A -p B B^{tree})
This basically acts like the (non-existent) merge -s theirs
strategy.
You can find the resulting history in the plumbing
branch of the demo repository
Not very readable and not as easy to remember compared to the -s ours
switch, but it does the job. The resulting tree is again the same as branch B:
$ git rev-parse A^{tree} B^{tree} HEAD^{tree}
3859ea064e85b2291d189e798bfa1bff87f51f3e
0389f8f2a3e560b639d82597a7bc5489a4c96d44
0389f8f2a3e560b639d82597a7bc5489a4c96d44
EDIT 2020-07-29:
There seems to be a lot of confusion as to what the difference between -s ours
and -X ours
(equivalent to -s recursive --strategy-option ours
) is. Here's a small example to show the two results from using the strategy vs the strategy option. I also recommend reading the question and answers of (Git Merging) When to use 'ours' strategy, 'ours' option and 'theirs' option?
First, setup a repository with 2 branches and 3 commits (1 base commit, and 1 commit per branch). You can find the sample repository on GitHub
$ git init
$ echo 'original' | tee file1 file2 file3
$ git commit -m 'initial commit'
$ git branch A
$ git branch B
$ git checkout A
$ echo 'A' > file1
$ git commit -m 'change on branch A' file1
$ git checkout B
$ echo 'B' > file2
$ git commit -m 'change on branch B' file2
Now, let's try the strategy option (doesn't really matter if we use theirs or ours for this explanation):
$ git merge -X ours A
$ cat file*
A
B
original
We end up with a merge of both branches' contents (branch "strategy-option" in the sample repo). Compare that to using the merge strategy (re-init your repository or reset branch, before executing the next steps):
$ git merge -s ours A
$ cat file*
original
B
original
The result is quite different (branch "merge-strategy" in the sample repo). With the strategy option, we get a merge result of both branches, with the strategy we throw away any changes which happened in the other branch.
You will also notice that the commit created by the merge-strategy in fact points to the exact same tree than the latest commit of "our" branch, while the strategy-option created a new, previously unseen tree:
$ git rev-parse A^{tree} B^{tree} merge-strategy^{tree} strategy-option^{tree}
3859ea064e85b2291d189e798bfa1bff87f51f3e
0389f8f2a3e560b639d82597a7bc5489a4c96d44
0389f8f2a3e560b639d82597a7bc5489a4c96d44
5b09d34a37a183723b409d25268c8cb4d073206e
OP indeed asked for "I no longer need the old changes in […] branch" and "So I just want to dump all the contents of [A] into [B]", which is not possible to do with a strategy option. Using the 'ours' merge strategy is one possibility of many, but likely the easiest (other possibilities include using low level commands of Git such as write-tree
and commit-tree
).
The __import__
function can be a bit hard to understand.
If you change
i = __import__('matplotlib.text')
to
i = __import__('matplotlib.text', fromlist=[''])
then i
will refer to matplotlib.text
.
In Python 2.7 and Python 3.1 or later, you can use importlib
:
import importlib
i = importlib.import_module("matplotlib.text")
Some notes
If you're trying to import something from a sub-folder e.g. ./feature/email.py
, the code will look like importlib.import_module("feature.email")
You can't import anything if there is no __init__.py
in the folder with file you are trying to import
Seems like the second column is set as a unique index. If you dont need that remove it and your errors will go away. Possibly you added the index by mistake and thats why you are seeing the errors today and werent seeing them yesterday
Try to do so:
1) In your index.html
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<a class="thumbnail" href="#">
<div class="ratio" style="background-image:url('../Images/img1.jpg')"></div>
</a>
</div>
2) In your style.css
.ratio {
position:relative;
width: 100%;
height: 0;
padding-bottom: 50%;
background-repeat: no-repeat;
background-position: center center;
background-size: cover;
}
I just had the same problem. In my case PHP code generated few times the same jQuery code and that was the multiple trigger.
<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zglos</a>
(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)
<script type="text/javascript">
$('.report').click(function(){...});
</script>
My solution was to separate script in another php file and load that file ONE TIME.
Modulo arithmetic with negative operands is defined by the language designer, who might leave it to the language implementation, who might defer the definition to the CPU architecture.
I wasn't able to find a Java language definition.
Thanks Ishtar, Java Language Specification for the Remainder Operator % says that the sign of the result is the same as the sign of the numerator.
Also u can consider this
$('#select_2').find('option:selected').text();
which might be a little faster solution though I am not sure.
In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) {
was returning an invalid character error because it was trying to watch the value of attrs.dynamic
which was html text.
I fixed that by fetching the attribute from the scope property
scope: { dynamic: '=dynamic'},
My example
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
In my case for Bootstrap4:
<body class="d-flex flex-column min-vh-100">
<div class="wrapper flex-grow-1"></div>
<footer></footer>
</body>
If your app is written in TypeScript, try
(global as any).logger = // ...
or
Object.assign(global, { logger: // ... })
However, I will do it only when React Native's __DEV__
in testing environment.
I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)
stackblitz demo
import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";
@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {
@Input("copy-clipboard")
public payload: string;
@Output("copied")
public copied: EventEmitter<string> = new EventEmitter<string>();
@HostListener("click", ["$event"])
public onClick(event: MouseEvent): void {
event.preventDefault();
if (!this.payload)
return;
let listener = (e: ClipboardEvent) => {
let clipboard = e.clipboardData || window["clipboardData"];
clipboard.setData("text", this.payload.toString());
e.preventDefault();
this.copied.emit(this.payload);
};
document.addEventListener("copy", listener, false)
document.execCommand("copy");
document.removeEventListener("copy", listener, false);
}
}
and then use it as such
<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
<i class="fa fa-clipboard"></i>
Copy
</a>
public notify(payload: string) {
// Might want to notify the user that something has been pushed to the clipboard
console.info(`'${payload}' has been copied to clipboard`);
}
Note: notice the window["clipboardData"]
is needed for IE as it does not understand e.clipboardData
I have not used pyserial but based on the API documentation at https://pyserial.readthedocs.io/en/latest/shortintro.html it seems like a very nice interface. It might be worth double-checking the specification for AT commands of the device/radio/whatever you are dealing with.
Specifically, some require some period of silence before and/or after the AT command for it to enter into command mode. I have encountered some which do not like reads of the response without some delay first.
A "quick and dirty" solution is to maintain a standard .md file using standard TeX equations, e.g. _README.md
.
When you are satisfied, pass the entire file through Pandoc to convert from standard Markdown
to Markdown (Github flavour)
, and copy the output to README.md
.
You can do this online for a quick turnaround, or install/configure Pandoc locally.
I hope this will work
EDITED
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="15dp" >
<ImageView
android:id="@+id/place_category_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:contentDescription="ss"
android:paddingTop="10dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/place_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="320" />
<TextView
android:id="@+id/place_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="15dp"
android:layout_toRightOf="@+id/place_category_icon"
android:text="Place Name"
android:textColor="#FFFF00"
android:textSize="14sp"
android:textStyle="bold" />
</RelativeLayout>
These days (May 2017), MATLAB still suffer from a robust method to export figures, especially in GNU/Linux systems when exporting figures in batch mode. The best option is to use the extension export_fig
Just download the source code from Github and use it:
plot(cos(linspace(0, 7, 1000)));
set(gcf, 'Position', [100 100 150 150]);
export_fig test2.png
XML:
<foo>
<bar>
<type foobar="1"/>
<type foobar="2"/>
</bar>
</foo>
Python code:
import xml.etree.cElementTree as ET
tree = ET.parse("foo.xml")
root = tree.getroot()
root_tag = root.tag
print(root_tag)
for form in root.findall("./bar/type"):
x=(form.attrib)
z=list(x)
for i in z:
print(x[i])
Output:
foo
1
2
We can use
public StreamWriter(string path, bool append);
while opening the file
string path="C:\\MyFolder\\Notes.txt"
StreamWriter writer = new StreamWriter(path, true);
First parameter is a string to hold a full file path Second parameter is Append Mode, that in this case is made true
Writing to the file can be done with:
writer.Write(string)
or
writer.WriteLine(string)
Sample Code
private void WriteAndAppend()
{
string Path = Application.StartupPath + "\\notes.txt";
FileInfo fi = new FileInfo(Path);
StreamWriter SW;
StreamReader SR;
if (fi.Exists)
{
SR = new StreamReader(Path);
string Line = "";
while (!SR.EndOfStream) // Till the last line
{
Line = SR.ReadLine();
}
SR.Close();
int x = 0;
if (Line.Trim().Length <= 0)
{
x = 0;
}
else
{
x = Convert.ToInt32(Line.Substring(0, Line.IndexOf('.')));
}
x++;
SW = new StreamWriter(Path, true);
SW.WriteLine("-----"+string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine(x.ToString() + "." + textBox1.Text);
}
else
{
SW = new StreamWriter(Path);
SW.WriteLine("-----" + string.Format("{0:dd-MMM-yyyy hh:mm:ss tt}", DateTime.Now));
SW.WriteLine("1." + textBox1.Text);
}
SW.Flush();
SW.Close();
}
Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:
LEFT OUTER JOIN or LEFT JOIN
RIGHT OUTER JOIN or RIGHT JOIN
FULL OUTER JOIN or FULL JOIN
From MSDN
The full outer join
or full join
returns all rows from both tables, matching up the rows wherever a match can be made and placing NULL
s in the places where no matching row exists.
you should use a /d before path as below :
cd /d e:\
For this true mysql style use this function below: 2019/02/28 15:33:12
function getDateTime() {_x000D_
var now = new Date(); _x000D_
var year = now.getFullYear();_x000D_
var month = now.getMonth()+1; _x000D_
var day = now.getDate();_x000D_
var hour = now.getHours();_x000D_
var minute = now.getMinutes();_x000D_
var second = now.getSeconds(); _x000D_
if(month.toString().length == 1) {_x000D_
month = '0'+month;_x000D_
}_x000D_
if(day.toString().length == 1) {_x000D_
day = '0'+day;_x000D_
} _x000D_
if(hour.toString().length == 1) {_x000D_
hour = '0'+hour;_x000D_
}_x000D_
if(minute.toString().length == 1) {_x000D_
minute = '0'+minute;_x000D_
}_x000D_
if(second.toString().length == 1) {_x000D_
second = '0'+second;_x000D_
} _x000D_
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second; _x000D_
return dateTime;_x000D_
}_x000D_
_x000D_
// example usage: realtime clock_x000D_
setInterval(function(){_x000D_
currentTime = getDateTime();_x000D_
document.getElementById("digital-clock").innerHTML = currentTime;_x000D_
}, 1000);
_x000D_
<div id="digital-clock"></div>
_x000D_
Let's change tütü's code
private void disableEnableControls(boolean enable, ViewGroup vg){
for (int i = 0; i < vg.getChildCount(); i++){
View child = vg.getChildAt(i);
if (child instanceof ViewGroup){
disableEnableControls(enable, (ViewGroup)child);
} else {
child.setEnabled(enable);
}
}
}
I think, there is no point in just making viewgroup disable. If you want to do it, there is another way I have used for exactly the same purpose. Create view as a sibling of your groupview :
<View
android:visibility="gone"
android:id="@+id/reservation_second_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:background="#66ffffff"
android:clickable="false" />
and at run-time, make it visible. Note: your groupview's parent layout should be either relative or frame layout. Hope this will help.
This helped me at the end:
Quick guide:
Download Google USB Driver
Connect your device with Android Debugging enabled to your PC
Open Device Manager of Windows from System Properties.
Your device should appear under Other devices
listed as something like
Android ADB Interface
or 'Android Phone' or similar. Right-click that and
click on Update Driver Software...
Select Browse my computer for driver software
Select Let me pick from a list of device drivers on my computer
Double-click Show all devices
Press the Have disk
button
Browse and navigate to [wherever your SDK has been installed]\google-usb_driver and select android_winusb.inf
Select Android ADB Interface
from the list of device types.
Press the Yes
button
Press the Install
button
Press the Close
button
Now you've got the ADB driver set up correctly. Reconnect your device if it doesn't recognize it already.
Yet another answer...but I usually find myself in a case, when I need to load data simultaneously and put it into variables, like:
var cats = new List<Cat>();
var dog = new Dog();
var loadDataTasks = new Task[]
{
Task.Run(async () => cats = await LoadCatsAsync()),
Task.Run(async () => dog = await LoadDogAsync())
};
try
{
await Task.WhenAll(loadDataTasks);
}
catch (Exception ex)
{
// handle exception
}
If anyone is also looking for how to get the name of the HTML tag, you can use "tagName": $(this)[0].tagName
You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.
We had the same issue while trying to launch Selenium tests from Jenkins. I had selected the 'Start Xvfb before the build, and shut it down after' box and passed in the necessary screen options, but I was still getting this error.
It finally worked when we passed in the following commands in the Execute Shell box.
Xvfb :99 -ac -screen 0 1280x1024x24 &
nice -n 10 x11vnc 2>&1 &
...
killall Xvfb
You can update the fragment in two different ways,
First way
like @Sajmon
You need to implement getItemPosition(Object obj)
method.
This method is called when you call
notifyDataSetChanged()
You can find a example in Github and more information in this post.
Second way
My approach to update fragments within the viewpager is to use the setTag()
method for any instantiated view in the instantiateItem()
method. So when you want to change the data or invalidate the view that you need, you can call the findViewWithTag()
method on the ViewPager to retrieve the previously instantiated view and modify/use it as you want without having to delete/create a new view each time you want to update some value.
@Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
mFragmentTags.put(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
String tag = mFragmentTags.get(position);
if (tag != null) {
fragment = mFragmentManager.findFragmentByTag(tag);
}
return fragment;
}
You can find a example in Github or more information in this post:
If you're willing to use IronPython, you can execute scripts directly in C#:
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(@"test.py");
}
I'm using nGram, too. I use standard tokenizer and nGram just as a filter. Here is my setup:
{
"index": {
"index": "my_idx",
"type": "my_type",
"analysis": {
"index_analyzer": {
"my_index_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"mynGram"
]
}
},
"search_analyzer": {
"my_search_analyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"standard",
"lowercase",
"mynGram"
]
}
},
"filter": {
"mynGram": {
"type": "nGram",
"min_gram": 2,
"max_gram": 50
}
}
}
}
}
Let's you find word parts up to 50 letters. Adjust the max_gram as you need. In german words can get really big, so I set it to a high value.
bind()
of INADDR_ANY
does NOT "generate a random IP". It binds the socket to all available interfaces.
For a server, you typically want to bind to all interfaces - not just "localhost".
If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");
, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...)
.
As it happens, INADDR_ANY
is a constant that happens to equal "zero":
http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html
# define INADDR_ANY ((unsigned long int) 0x00000000)
...
# define INADDR_NONE 0xffffffff
...
# define INPORT_ANY 0
...
If you're not already familiar with it, I urge you to check out Beej's Guide to Sockets Programming:
Since people are still reading this, an additional note:
When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2).
In this case, only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.
When listen(2) is called on an unbound socket, the socket is automatically bound to a random free port with the local address set to INADDR_ANY.
When connect(2) is called on an unbound socket, the socket is automatically bound to a random free port or to a usable shared port with the local address set to INADDR_ANY...
There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding...
Also:
bind() — Bind a name to a socket:
If the (sin_addr.s_addr) field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.
Create /res/drawable/button.xml
with the following content :
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
<solid android:color="#90EE90"/>
<corners
android:bottomRightRadius="3dp"
android:bottomLeftRadius="3dp"
android:topLeftRadius="3dp"
android:topRightRadius="3dp"/>
</shape>
And then you can use the following :
<Button
android:id="@+id/button_save_prefs"
android:text="@string/save"
android:background="@drawable/button"/>
If you are looking for a better way to handle SQLException, there are a couple things you could do. First, Spring.NET does something similar to what you are looking for (I think). Here is a link to what they are doing:
http://springframework.net/docs/1.2.0/reference/html/dao.html
Also, instead of looking at the message, you could check the error code (sqlEx.Number
). That would seem to be a better way of identifying which error occurred. The only problem is that the error number returned might be different for each database provider. If you plan to switch providers, you will be back to handling it the way you are or creating an abstraction layer that translates this information for you.
Here is an example of a guy who used the error code and a config file to translate and localize user-friendly error messages:
This is the format of /etc/crontab:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.
To run something every minute:
* * * * * username /var/www/html/a.php
To run something at midnight of every day:
0 0 * * * username /var/www/html/reset.php
You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:
chmod +x file.php
Start your php file with a shebang so that your shell knows which interpreter to use:
#!/usr/bin/php
<?php
// your code here
Even you run from Administrator, it may not solve the issue if the pip is installed inside another userspace. This is because Administrator doesn't own another's userspace directory, thus he can't see (go inside) the inside of the directory that is owned by somebody. Below is an exact solution.
python -m pip install -U pip --user //In Windows
Note: You should provide --user option
pip install -U pip --user //Linux, and MacOS
Use this to get time from 00:00:00 to 23:59:59
If your time is having date from it by using 'LT or LTS'
var now = moment('23:59:59','HHmmss').format("HH:mm:ss")
Google is my friend and it showed me this page:
I know there area lot of correct answers here, with respect to all of them I introduce this hack :
In StartUp.cs
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
and then everywhere you need HttpContext you can use :
httpContext = new HttpContextAccessor().HttpContext;
Hope it helps ;)
If you do have a TemplateField
inside the columns of your GridView
and you have, say, a control named blah bound to it. Then place the outlook_id
as a HiddenField
there like this:
<asp:TemplateField HeaderText="OutlookID">
<ItemTemplate>
<asp:Label ID="blah" runat="server">Existing Control</asp:Label>
<asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
Now, grab the row in the event you want the outlook_id
and then access the control.
For RowDataBound
access it like:
string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;
Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.
When you are inside an activity and need to go to a fragment use below
getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
But when you are inside a fragment and need to go to a fragment then just add a getActivity().
before, so it would become
getActivity().getFragmentManager().beginTransaction().replace(R.id.*TO_BE_REPLACED_LAYOUT_ID*, new tasks()).commit();
as simple as that.
The *TO_BE_REPLACED_LAYOUT_ID*
can be the entire page of activity or a part of it, just make sure to put an id to the layout to be replaced. It is general practice to put the replaceable layout in a FrameLayout
.
You just have to set UIFileSharingEnabled
(Application Supports iTunes file sharing
) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.
In the past, it was also necessary to define CFBundleDisplayName
(Bundle Display Name
), if it wasn't already there. More details here.
A thread is a set of (CPU)instructions which can be executed.
But in order to better understand the thread we have to have some knowledge about how the CPU and RAM works.
A computer follows instructions and manipulates data. RAM is the place where those instructions and data on which the CPU will operate on, are saved. Within the CPU some memory cells called registers exist. Those registers contain numbers on which the CPU performs simple mathematical operations. An example can be the following: “Add the number in register #3 to the number in register #1.”.
The collection of all operations a CPU can do is called instruction set. Each operation in the instruction set is assigned a number, so computer code is essentially a sequence of numbers representing CPU operations. These operations are stored as numbers in the RAM.
The CPU works in a never-ending loop, always fetching and executing an instruction from memory. At the core of this cycle is the PC register, or Program Counter. It's a special register that stores the memory address of the next instruction to be executed.
The CPU will:
The CPU can be instructed to write a new value to the PC, causing the execution to branch, or "jump" to somewhere else in the memory. And this branching can be conditional. For instance, a CPU instruction could say: "set PC to address #200 if register #1 equals zero". This allows computers to execute stuff like this:
if x = 0
compute_this()
else
compute_that()
Resources taken from Computer Science Distilled were used.