A generative algorithm models how the data was generated in order to categorize a signal. It asks the question: based on my generation assumptions, which category is most likely to generate this signal?
A discriminative algorithm does not care about how the data was generated, it simply categorizes a given signal.
I am giving a very simple code, which i used in my solution (I have the same problem statement as yours)
SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con))
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();
I have given a predefined table-name as "abcd" (you must take care that a table by this name doesn't exist in your database). Please vote my answer if it works for you!!!! :)
Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}
. If you left the routing as the default {controller}/{action}/{id}
in your global.asax.cs
file, then you will need to pass in id
.
routes.MapRoute(
"Inventory",
"Inventory/{action}/{firstItem}",
new { controller = "Inventory", action = "ListAll", firstItem = "" }
);
... or something close to that.
$ sbt sbtVersion
This prints the sbt version used in your current project, or if it is a multi-module project for each module.
$ sbt 'inspect sbtVersion'
[info] Set current project to jacek (in build file:/Users/jacek/)
[info] Setting: java.lang.String = 0.13.1
[info] Description:
[info] Provides the version of sbt. This setting should be not be modified.
[info] Provided by:
[info] */*:sbtVersion
[info] Defined at:
[info] (sbt.Defaults) Defaults.scala:68
[info] Delegates:
[info] *:sbtVersion
[info] {.}/*:sbtVersion
[info] */*:sbtVersion
[info] Related:
[info] */*:sbtVersion
You may also want to use sbt about
that (copying Mark Harrah's comment):
The about command was added recently to try to succinctly print the most relevant information, including the sbt version.
A lazy val is most easily understood as a "memoized (no-arg) def".
Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.
As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.
Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:
http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html
Here is a common use case using class-based components: The parent component provides a callback function, the child component renders the input box, and when the user presses Enter, we pass the user's input to the parent.
class ParentComponent extends React.Component {
processInput(value) {
alert('Parent got the input: '+value);
}
render() {
return (
<div>
<ChildComponent handleInput={(value) => this.processInput(value)} />
</div>
)
}
}
class ChildComponent extends React.Component {
constructor(props) {
super(props);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleKeyDown(e) {
if (e.key === 'Enter') {
this.props.handleInput(e.target.value);
}
}
render() {
return (
<div>
<input onKeyDown={this.handleKeyDown} />
</div>
)
}
}
This question has been answered sufficiently many times, but with C# 7.2 and the introduction of the Span type, there is a faster way to do this in unsafe code:
public static class StringSupport
{
private static readonly int _charSize = sizeof(char);
public static unsafe byte[] GetBytes(string str)
{
if (str == null) throw new ArgumentNullException(nameof(str));
if (str.Length == 0) return new byte[0];
fixed (char* p = str)
{
return new Span<byte>(p, str.Length * _charSize).ToArray();
}
}
public static unsafe string GetString(byte[] bytes)
{
if (bytes == null) throw new ArgumentNullException(nameof(bytes));
if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
if (bytes.Length == 0) return string.Empty;
fixed (byte* p = bytes)
{
return new string(new Span<char>(p, bytes.Length / _charSize));
}
}
}
Keep in mind that the bytes represent a UTF-16 encoded string (called "Unicode" in C# land).
Some quick benchmarking shows that the above methods are roughly 5x faster than their Encoding.Unicode.GetBytes(...)/GetString(...) implementations for medium sized strings (30-50 chars), and even faster for larger strings. These methods also seem to be faster than using pointers with Marshal.Copy(..) or Buffer.MemoryCopy(...).
At times, if we forget the
return self.cleaned_data
in the clean function of django forms, we will not have any data though the form.is_valid()
will return True
.
The best version of this I've found on Windows is Joseph Newcomer's "whereis" utility, which is available (with source) from his site.
The article about the development of "whereis" is worth reading.
Generally to count distinct values in single column, you can use Series.value_counts
:
df.domain.value_counts()
#'vk.com' 5
#'twitter.com' 2
#'facebook.com' 1
#'google.com' 1
#Name: domain, dtype: int64
To see how many unique values in a column, use Series.nunique
:
df.domain.nunique()
# 4
To get all these distinct values, you can use unique
or drop_duplicates
, the slight difference between the two functions is that unique
return a numpy.array
while drop_duplicates
returns a pandas.Series
:
df.domain.unique()
# array(["'vk.com'", "'twitter.com'", "'facebook.com'", "'google.com'"], dtype=object)
df.domain.drop_duplicates()
#0 'vk.com'
#2 'twitter.com'
#4 'facebook.com'
#6 'google.com'
#Name: domain, dtype: object
As for this specific problem, since you'd like to count distinct value with respect to another variable, besides groupby
method provided by other answers here, you can also simply drop duplicates firstly and then do value_counts()
:
import pandas as pd
df.drop_duplicates().domain.value_counts()
# 'vk.com' 3
# 'twitter.com' 2
# 'facebook.com' 1
# 'google.com' 1
# Name: domain, dtype: int64
Look here for the answer by TheMattster. I implemented it and it worked like a charm. In a nutshell, his solution suggests to add the COM dll as a resource to the project (so now it compiles into the project's dll), and upon the first run write it to a file (i.e. the dll file I wanted there in the first place).
The following is taken from his answer.
Step 1) Add the DLL as a resource (below as "Resources.DllFile"). To do this open project properties, select the resources tab, select "add existing file" and add the DLL as a resource.
Step 2) Add the name of the DLL as a string resource (below as "Resources.DllName").
Step 3) Add this code to your main form-load:
if (!File.Exists(Properties.Resources.DllName))
{
var outStream = new StreamWriter(Properties.Resources.DllName, false);
var binStream = new BinaryWriter(outStream.BaseStream);
binStream.Write(Properties.Resources.DllFile);
binStream.Close();
}
My problem was that not only I had to use the COM dll in my project, I also had to deploy it with my app using ClickOnce, and without being able to add reference to it in my project the above solution is practically the only one that worked.
Here are two functions to calculate distance and bearing, which are based on the code in previous messages and https://gist.github.com/jeromer/2005586 (added tuple type for geographical points in lat, lon format for both functions for clarity). I tested both functions and they seem to work right.
#coding:UTF-8
from math import radians, cos, sin, asin, sqrt, atan2, degrees
def haversine(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = pointA[0]
lon1 = pointA[1]
lat2 = pointB[0]
lon2 = pointB[1]
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def initial_bearing(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = radians(pointA[0])
lat2 = radians(pointB[0])
diffLong = radians(pointB[1] - pointA[1])
x = sin(diffLong) * cos(lat2)
y = cos(lat1) * sin(lat2) - (sin(lat1)
* cos(lat2) * cos(diffLong))
initial_bearing = atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
pA = (46.2038,6.1530)
pB = (46.449, 30.690)
print haversine(pA, pB)
print initial_bearing(pA, pB)
Most comprehensive article on the different options with pros and cons:
Source: https://sunscrapers.com/blog/where-to-put-business-logic-django/
Another way to do this would be to respond to the UITableViewDelegate
method willDisplayHeaderView
. The passed view is actually an instance of a UITableViewHeaderFooterView
.
The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection
to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView
method.)
You could then respond to the titleForHeaderInSection
method to reuse this configured header with different section titles.
Objective-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Note: if your view controller is a descendant of a UITableViewController
, this would need to be declared as override func
.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.frame
header.textLabel?.textAlignment = .center
}
There are some really good answers on here. Let me post a different way to set your headers with the WebClient(). I will also show you how to set an API key.
var client = new WebClient();
string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}";
//If you have your data stored in an object serialize it into json to pass to the webclient with Newtonsoft's JsonConvert
var encodedJson = JsonConvert.SerializeObject(newAccount);
client.Headers.Add($"x-api-key:{ApiKey}");
client.Headers.Add("Content-Type:application/json");
try
{
var response = client.UploadString($"{apiurl}", encodedJson);
//if you have a model to deserialize the json into Newtonsoft will help bind the data to the model, this is an extremely useful trick for GET calls when you have a lot of data, you can strongly type a model and dump it into an instance of that class.
Response response1 = JsonConvert.DeserializeObject<Response>(response);
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
This answer may be premature, but deno supports running both TS and JS out of the box.
Based on your development environment, moving to Deno (and learning about it) might be too much, but hopefully this answer helps someone in the future.
Three simple choices.
Obvious
x, _ = func()
x, junk = func()
Hideous
x = func()[0]
And there are ways to do this with a decorator.
def val0( aFunc ):
def pick0( *args, **kw ):
return aFunc(*args,**kw)[0]
return pick0
func0= val0(func)
If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.
Add shadow-layout to your Gradle file:
dependencies {
compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}
At the top the xml layout where you have your button, add to the top:
xmlns:app="http://schemas.android.com/apk/res-auto"
it will make available the custom attributes.
Then you put a shadow layout around you Button:
<com.dd.ShadowLayout
android:layout_marginTop="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:sl_shadowRadius="4dp"
app:sl_shadowColor="#AA000000"
app:sl_dx="0dp"
app:sl_dy="0dp"
app:sl_cornerRadius="56dp">
<YourButton
.... />
</com.dd.ShadowLayout>
You can then tweak the app:
settings to match your required shadow.
Hope it helps.
Maybe
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty)
.Where(l => l.InternalName != string.Empty)
?
You can probably also put it in the same where clause:
x=> x.Lists.Include(l => l.Title)
.Where(l => l.Title != string.Empty && l.InternalName != string.Empty)
Had a similar problem. Solved it by calling ToList() on the entity collection and querying the list. If the collection is small this is an option.
IQueryable<entity> pages = context.pages.ToList().Where(p=>p.serial == item.Key.ToString())
Hope this helps.
Start your IDE with administrative privilege( Windows: right click and run as admin), so that it has read write access to tomact folder for deployment. It worked for me.
Yes, it's OK - it's just like using it in an if
statement. Of course, you can't use a break
to break out of a loop from inside a switch.
Update September 2015 (6 years later)
The last release of git-for-Windows (2.5.3) now includes:
By configuring
git config core.editor notepad
, users can now usenotepad.exe
as their default editor.
Configuringgit config format.commitMessageColumns 72
will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.
See commit 69b301b by Johannes Schindelin (dscho
).
And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor opens to a hidden window or somewhere obscure and the user gets lost.
See commit abfb04d (07 Dec 2017), and commit a64f213 (29 Nov 2017) by Lars Schneider (larsxschneider
).
Helped-by: Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit 0c69a13, 19 Dec 2017)
launch_editor()
: indicate that Git waits for user inputWhen a graphical
GIT_EDITOR
is spawned by a Git command that opens and waits for user input (e.g. "git rebase -i
"), then the editor window might be obscured by other windows.
The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging.Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line
Original answer
I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1
I prefer to not have to set an EDITOR variable, so I tried:
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"
That always gives:
C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.
If I define a npp.bat including:
"c:\Program Files\Notepad++\notepad++.exe" %*
and I type:
C:\prog\git>git config --global core.editor C:\prog\git\npp.bat
It just works from the DOS session, but not from the git shell.
(not that with the core.editor configuration mechanism, a script with "start /WAIT...
" in it would not work, but only open a new DOS window)
Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes. Note the direction of the slashes! Use /
NOT \
to separate folders in the path name!
git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Or if you are in a 64 bit system:
git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config
.
The actual solution (with a script) was to realize that:
what you refer to in the config file is actually a shell (/bin/sh
) script, not a DOS script.
So what does work is:
C:\prog\git>git config --global core.editor C:/prog/git/npp.bat
with C:/prog/git/npp.bat
:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
or
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"
With that setting, I can do 'git config --global --edit
' from DOS or Git Shell, or I can do 'git rebase -i ...
' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the -multiInst
' option), and wait for that instance to be closed before going on.
Note that I use only '/', not \
'. And I installed msysgit using option 2. (Add the git\bin
directory to the PATH
environment variable, but without overriding some built-in windows tools)
The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the [git]\cmd
directory though (or in any directory referenced by your PATH environment variable).
See also:
lightfire228 adds in the comments:
For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "Aborting commit due to empty message": change your
.bat
or.sh
file to say:
"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>.
That will tell notepad++ to open the temp commit file, rather than a blank new one.
Many commands are already attached to simple ctrl+[key], you can also do chorded keybinding like ctrl a+b.
(In case this is your first time reading about chorded keybindings: They work by not letting go of the ctrl key and pressing a second key after the first.)
I have my Emmet: Wrap with Abbreviation
bound to ((ctrl) (w+a)).
In windows: File > Preferences > Keyboard Shortcuts ((ctrl) (k+s))> search for Wrap with Abbreviation > double-click > add your combonation.
If you wanted to do it that way...
$line = 0;
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// This is the second line.
break;
}
$line++;
}
Alternatively, open it with file()
and subscript the line with [1]
.
you should be searching about how to add favicon.ico
. You can try adding favicon.ico
directly in your html pages like this
<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />
Or you can update that in your webserver
. It is advised to add in your webserver
as you don't need to add this in each of your html
pages (assuming no includes
).
To add in your apache
place the favicon.ico
in your root website director and add this in httpd.conf
AddType image/x-icon .ico
There are two ways this could be achieved.
DateTimeFormat
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss").parseDateTime("04/02/2011 20:27:05");
SimpleDateFormat
String dateValue = "04/02/2011 20:27:05";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); // 04/02/2011 20:27:05
Date date = sdf.parse(dateValue); // returns date object
System.out.println(date); // outputs: Fri Feb 04 20:27:05 IST 2011
In phpMyAdmin, click the table, and then click the Import tab at the top of the page.
Browse and open the csv file. Leave the charset as-is. Uncheck partial import unless you have a HUGE dataset (or slow server). The format should already have selected “CSV” after selecting your file, if not then select it (not using LOAD DATA). If you want to clear the whole table before importing, check “Replace table data with file”. Optionally check “Ignore duplicate rows” if you think you have duplicates in the CSV file. Now the important part, set the next four fields to these values:
Fields terminated by: ,
Fields enclosed by: “
Fields escaped by: \
Lines terminated by: auto
Currently these match the defaults except for “Fields terminated by”, which defaults to a semicolon.
Now click the Go button, and it should run successfully.
I expanded a bit on RajaShilpa's answer. You can use syntax like:
{{object | sumOfTwoValues:'quantity':'products.productWeight'}}
so that you can access an object's child object. Here is the code for the filter:
.filter('sumOfTwoValues', function () {
return function (data, key1, key2) {
if (typeof (data) === 'undefined' || typeof (key1) === 'undefined' || typeof (key2) === 'undefined') {
return 0;
}
var keyObjects1 = key1.split('.');
var keyObjects2 = key2.split('.');
var sum = 0;
for (i = 0; i < data.length; i++) {
var value1 = data[i];
var value2 = data[i];
for (j = 0; j < keyObjects1.length; j++) {
value1 = value1[keyObjects1[j]];
}
for (k = 0; k < keyObjects2.length; k++) {
value2 = value2[keyObjects2[k]];
}
sum = sum + (value1 * value2);
}
return sum;
}
});
If under "last record" you mean the record which has the latest timestamp value, then try this:
my_query = client.query("
SELECT TIMESTAMP,
value,
card
FROM my_table
ORDER BY TIMESTAMP DESC
LIMIT 1
");
Both of them behave differently when it comes to dynamic data handling.
If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.
$a = NULL;
$c = '';
print $a ?? '1b';
print "\n";
print $a ?: '2b';
print "\n";
print $c ?? '1d';
print "\n";
print $c ?: '2d';
print "\n";
print $e ?? '1f';
print "\n";
print $e ?: '2f';
And the output:
1b
2b
2d
1f
Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f
Link: https://3v4l.org/ZBAa1
Is this a local custom CSS file? Is this your website? Maybe you should clear your cache.
Also the last CSS declaration takes precedence.
How inheritance can be dangerous ?
Lets take an example
public class X{
public void do(){
}
}
Public Class Y extends X{
public void work(){
do();
}
}
1) As clear in above code , Class Y has very strong coupling with class X. If anything changes in superclass X , Y may break dramatically. Suppose In future class X implements a method work with below signature
public int work(){
}
Change is done in class X but it will make class Y uncompilable. SO this kind of dependency can go up to any level and it can be very dangerous. Every time superclass might not have full visibility to code inside all its subclasses and subclass may be keep noticing what is happening in superclass all the time. So we need to avoid this strong and unnecessary coupling.
How does composition solves this issue?
Lets see by revising the same example
public class X{
public void do(){
}
}
Public Class Y{
X x = new X();
public void work(){
x.do();
}
}
Here we are creating reference of X class in Y class and invoking method of X class by creating an instance of X class. Now all that strong coupling is gone. Superclass and subclass are highly independent of each other now. Classes can freely make changes which were dangerous in inheritance situation.
2) Second very good advantage of composition in that It provides method calling flexibility, for example :
class X implements R
{}
class Y implements R
{}
public class Test{
R r;
}
In Test class using r reference I can invoke methods of X class as well as Y class. This flexibility was never there in inheritance
3) Another great advantage : Unit testing
public class X {
public void do(){
}
}
Public Class Y {
X x = new X();
public void work(){
x.do();
}
}
In above example, if state of x instance is not known, it can easily be mocked up by using some test data and all methods can be easily tested. This was not possible at all in inheritance as you were heavily dependent on superclass to get the state of instance and execute any method.
4) Another good reason why we should avoid inheritance is that Java does not support multiple inheritance.
Lets take an example to understand this :
Public class Transaction {
Banking b;
public static void main(String a[])
{
b = new Deposit();
if(b.deposit()){
b = new Credit();
c.credit();
}
}
}
Good to know :
composition is easily achieved at runtime while inheritance provides its features at compile time
composition is also know as HAS-A relation and inheritance is also known as IS-A relation
So make it a habit of always preferring composition over inheritance for various above reasons.
This is copied from my answer to another very similar post, hope it can help:
1) Start with maximum number of threads a system can support:
int Num_Threads = thread::hardware_concurrency();
2) For an efficient threadpool implementation, once threads are created according to Num_Threads, it's better not to create new ones, or destroy old ones (by joining). There will be performance penalty, might even make your application goes slower than the serial version.
Each C++11 thread should be running in their function with an infinite loop, constantly waiting for new tasks to grab and run.
Here is how to attach such function to the thread pool:
int Num_Threads = thread::hardware_concurrency();
vector<thread> Pool;
for(int ii = 0; ii < Num_Threads; ii++)
{ Pool.push_back(thread(Infinite_loop_function));}
3) The Infinite_loop_function
This is a "while(true)" loop waiting for the task queue
void The_Pool:: Infinite_loop_function()
{
while(true)
{
{
unique_lock<mutex> lock(Queue_Mutex);
condition.wait(lock, []{return !Queue.empty() || terminate_pool});
Job = Queue.front();
Queue.pop();
}
Job(); // function<void()> type
}
};
4) Make a function to add job to your Queue
void The_Pool:: Add_Job(function<void()> New_Job)
{
{
unique_lock<mutex> lock(Queue_Mutex);
Queue.push(New_Job);
}
condition.notify_one();
}
5) Bind an arbitrary function to your Queue
Pool_Obj.Add_Job(std::bind(&Some_Class::Some_Method, &Some_object));
Once you integrate these ingredients, you have your own dynamic threading pool. These threads always run, waiting for job to do.
I apologize if there are some syntax errors, I typed these code and and I have a bad memory. Sorry that I cannot provide you the complete thread pool code, that would violate my job integrity.
Edit: to terminate the pool, call the shutdown() method:
XXXX::shutdown(){
{
unique_lock<mutex> lock(threadpool_mutex);
terminate_pool = true;} // use this flag in condition.wait
condition.notify_all(); // wake up all threads.
// Join all threads.
for(std::thread &every_thread : thread_vector)
{ every_thread.join();}
thread_vector.clear();
stopped = true; // use this flag in destructor, if not set, call shutdown()
}
For me the thing that worked was the order in which the namespaces were defined in the xsi:schemaLocation tag : [ since the version was all good and also it was transaction-manager already ]
The error was with :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
AND RESOLVED WITH :
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
Use
//$arr should be array as you mentioned as below
foreach($arr as $key=>$value){
echo $value->sm_id;
}
OR
//$arr should be array as you mentioned as below
foreach($arr as $value){
echo $value->sm_id;
}
This can be done with CSS3:
<input type="text" />
input
{
-moz-border-radius: 15px;
border-radius: 15px;
border:solid 1px black;
padding:5px;
}
However, an alternative would be to put the input
inside a div
with a rounded background, and no border on the input
What about
ls {*.py,*.html}
It lists out all the files ending with .py or .html in their filenames
here is a quick review and with a simple and quick understanding
from teacher Beau Carnes from freecodecamp
If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.
(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)
There is no clean way to do this and like @Nick mentioned above it might just be easier to use the old school way of loops as then you can control this. But if you want to stick with what you got there is one way you could handle this. I'm sure I will get some heat for this one. But...
One way you could do what you want without an if statement is to raise an error and wrap your loop with a try/catch block:
try{
$(sentences).each(function() {
var s = this;
alert(s);
$(words).each(function(i) {
if (s.indexOf(this) > -1)
{
alert('found ' + this);
throw "Exit Error";
}
});
});
}
catch (e)
{
alert(e)
}
Ok, let the thrashing begin.
This can be done just by using a combination of getElementbyId, Select(), blur() and the copy command.
Note
The select() method selects all the text in a <textarea> element or an <input> element with a text field. This might not work on a button.
Usage
let copyText = document.getElementById('input-field');
copyText.select()
document.execCommand("copy");
copyReferal.blur()
document.getElementbyId('help-text').textContent = 'Copied'
The blur() method will remove the ugly highlighted portion instead of that you can show at beautiful message that your content was copied successfully.
Your syntax should work, maybe add a space between the colums like
SELECT something + ' ' + somethingElse as onlyOneColumn FROM someTable
Got hit by the same issue while accessing SQLServer from IIS. Adding TrustServerCertificate=True didnot help.
Could see a comment in MS docs: Make sure the SQLServer service account has access to the TLS Certificate you are using. (NT Service\MSSQLSERVER)
Open personal store and right click on the certificate -> manage private keys -> Add the SQL service account and give full control.
Restart the SQL service. It worked.
try this code in here...this is done using javascript onKeyUp() function...
<script>
function toCount(entrance,exit,text,characters) {
var entranceObj=document.getElementById(entrance);
var exitObj=document.getElementById(exit);
var length=characters - entranceObj.value.length;
if(length <= 0) {
length=0;
text='<span class="disable"> '+text+' <\/span>';
entranceObj.value=entranceObj.value.substr(0,characters);
}
exitObj.innerHTML = text.replace("{CHAR}",length);
}
</script>
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
Explanation with an example:
Consider you have a game (iso) image in your computer.
When you run
(mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]
But when you stop
(similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]
And when you do start
(similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]
In this example - The game image is your Docker image and virtual drive is your container.
The extglob
shell option gives you more powerful pattern matching in the command line.
You turn it on with shopt -s extglob
, and turn it off with shopt -u extglob
.
In your example, you would initially do:
$ shopt -s extglob
$ cp !(*Music*) /target_directory
The full available extended globbing operators are (excerpt from man bash
):
If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized.A pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:
- ?(pattern-list)
Matches zero or one occurrence of the given patterns- *(pattern-list)
Matches zero or more occurrences of the given patterns- +(pattern-list)
Matches one or more occurrences of the given patterns- @(pattern-list)
Matches one of the given patterns- !(pattern-list)
Matches anything except one of the given patterns
So, for example, if you wanted to list all the files in the current directory that are not .c
or .h
files, you would do:
$ ls -d !(*@(.c|.h))
Of course, normal shell globing works, so the last example could also be written as:
$ ls -d !(*.[ch])
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
If you are using npm you can use the shelljs package
To install: npm install [-g] shelljs
var shell = require('shelljs');
shell.ls('*.js').forEach(function (file) {
// do something
});
See more: https://www.npmjs.com/package/shelljs
The two common approaches are either that the class should have a constructor for the DAL to use, or the DAL should use reflection to hydrate objects.
I think you can do this with the hyperref
package, although I've not tried it myself. From the relevant LaTeX Wikibook section:
The
hyperref
package introduces another useful command;\autoref{}
. This command creates a reference with additional text corresponding to the targets type, all of which will be a hyperlink. For example, the command\autoref{sec:intro}
would create a hyperlink to the\label{sec:intro}
command, wherever it is. Assuming that this label is pointing to a section, the hyperlink would contain the text "section 3.4", or similar (capitalization rules will be followed, which makes this very convenient). You can customize the prefixed text by redefining\typeautorefname
to the prefix you want, as in:
\def\subsectionautorefname{section}
... or you could avoid the .
and $
constructions by using pipelining:
third xs = xs |> tail |> tail |> head
That's after you've added in the helper function:
(|>) x y = y x
As noted above in many of the other answers, there are many good packages that connect to the XLS/X file and get the data in a reasonable way. However, you should be warned that under no circumstances should you use the clipboard (or a .csv) file to retrieve data from Excel. To see why, enter =1/3
into a cell in excel. Now, reduce the number of decimal points visible to you to two. Then copy and paste the data into R. Now save the CSV. You'll notice in both cases Excel has helpfully only kept the data that was visible to you through the interface and you've lost all of the precision in your actual source data.
In the thread dump you can find the Line Number as below.
for the main thread which is currently running...
"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
java.lang.Thread.State: **RUNNABLE**
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:313)
at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**
Tried Class PropertiesLoaderUtils ?
This approach uses no annotation of Spring boot. A traditional Class way.
example:
Resource resource = new ClassPathResource("/application.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
String url_server=props.getProperty("server_url");
Use getProperty() method to pass the key and access the value in the properties file.
An Easy way to do it is the next but is necessary ensure that the amount parameter is given as a string.
function truncate(amountAsString, decimals = 2){
var dotIndex = amountAsString.indexOf('.');
var toTruncate = dotIndex !== -1 && ( amountAsString.length > dotIndex + decimals + 1);
var approach = Math.pow(10, decimals);
var amountToTruncate = toTruncate ? amountAsString.slice(0, dotIndex + decimals +1) : amountAsString;
return toTruncate
? Math.floor(parseFloat(amountToTruncate) * approach ) / approach
: parseFloat(amountAsString);
}
console.log(truncate("7.99999")); //OUTPUT ==> 7.99
console.log(truncate("7.99999", 3)); //OUTPUT ==> 7.999
console.log(truncate("12.799999999999999")); //OUTPUT ==> 7.99
Use groupby
and idxmax
methods:
transfer col date
to datetime
:
df['date']=pd.to_datetime(df['date'])
get the index of max
of column date
, after groupyby ad_id
:
idx=df.groupby(by='ad_id')['date'].idxmax()
get the wanted data:
df_max=df.loc[idx,]
Out[54]:
ad_id price date
7 22 2 2018-06-11
6 23 2 2018-06-22
2 24 2 2018-06-30
3 28 5 2018-06-22
It depends on the implementation of your JSON writer/parser. Microsoft's DataContractJsonSerializer seems to have a hard limit around 8kb (8192 I think), and it will error out for larger strings.
Edit: We were able to resolve the 8K limit for JSON strings by setting the MaxJsonLength property in the web config as described in this answer: https://stackoverflow.com/a/1151993/61569
I've decided to give an answer to this question because I think it can be solved using a simpler syntax than the convoluted try-catch block. The Laravel documentation is pretty brief on this subject.
Instead of using try-catch, you can just use the DB::transaction(){...}
wrapper like this:
// MyController.php
public function store(Request $request) {
return DB::transaction(function() use ($request) {
$user = User::create([
'username' => $request->post('username')
]);
// Add some sort of "log" record for the sake of transaction:
$log = Log::create([
'message' => 'User Foobar created'
]);
// Lets add some custom validation that will prohibit the transaction:
if($user->id > 1) {
throw AnyException('Please rollback this transaction');
}
return response()->json(['message' => 'User saved!']);
});
};
You should then see that the User and the Log record cannot exist without eachother.
Some notes on the implementation above:
return
the transaction, so that you can use the response()
you return within its callback.throw
an exception if you want the transaction to be rollbacked (or have a nested function that throws the exception for you automatically, like an SQL exception from within Eloquent).id
, updated_at
, created_at
and any other fields are AVAILABLE AFTER CREATION for the $user
object (for the duration of this transaction). The transaction will run through any of the creation logic you have. HOWEVER, the whole record is discarded when the AnyException
is thrown. This means that for instance an auto-increment column for id
does get incremented on failed transactions.Tested on Laravel 5.8
If all you are doing is replacing the existing data, then you can do this
std::vector<int> data; // evil global :)
void CopyData(int *newData, size_t count)
{
data.assign(newData, newData + count);
}
Its boils down to this: math.h
is from C
and was created over 10 years ago. In math.h, due to its primitive nature, the abs()
function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs()
.
When C++ was created it took math.h
and made it cmath
. cmath
is essentially math.h but improved for C++. It improved things like having to distinguish between fabs()
and abs, and just made abs()
for both doubles and integer types.
In summary either:
Use math.h and use abs()
for integers, fabs()
for doubles
or
use cmath and just have abs for everything (easier and recommended)
Hope this helps anyone who is having the same problem!
You have to do following steps.
Go to IIS ->
Sites->
Click on Your Web site ->
In Action Click on Edit Permissions ->
Security ->
Click on ADD ->
Advanced ->
Find Now ->
Add all the users in it ->
and grant all permissions to other users ->
click on Ok.
If you do above things properly you can access your web site by using your domain.
Suggestion - Do not add host name to your site it creates problem sometime. So please host your web site using your machines ip address.
That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.
The names of constants in interface types should be, and
final
variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore"_"
characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants includeMIN_VALUE
,MAX_VALUE
,MIN_RADIX
, andMAX_RADIX
of the classCharacter
.A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:
interface ProcessStates { int PS_RUNNING = 0; int PS_SUSPENDED = 1; }
Obscuring involving constant names is rare:
- Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
- Constant names cannot obscure method names, because they are distinguished syntactically.
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
<input type="button" id="btnTexWrapped" style="background:
url('http://i0006.photobucket.com/albums/0006/findstuff22/Backgrounds/bokeh2backgrounds.jpg');background-size:30px;width:50px;height:3em;" />
Change input style elements as you want to get the button you need.
I hope it was helpful.
(Git 2.22, Q2 2019, has introduced git submodule set-branch --branch aBranch -- <submodule_path>
)
Note that if you have an existing submodule which isn't tracking a branch yet, then (if you have git 1.8.2+):
Make sure the parent repo knows that its submodule now tracks a branch:
cd /path/to/your/parent/repo
git config -f .gitmodules submodule.<path>.branch <branch>
Make sure your submodule is actually at the latest of that branch:
cd path/to/your/submodule
git checkout -b branch --track origin/branch
# if the master branch already exist:
git branch -u origin/master master
(with 'origin' being the name of the upstream remote repo the submodule has been cloned from.
A git remote -v
inside that submodule will display it. Usually, it is 'origin')
Don't forget to record the new state of your submodule in your parent repo:
cd /path/to/your/parent/repo
git add path/to/your/submodule
git commit -m "Make submodule tracking a branch"
Subsequent update for that submodule will have to use the --remote
option:
# update your submodule
# --remote will also fetch and ensure that
# the latest commit from the branch is used
git submodule update --remote
# to avoid fetching use
git submodule update --remote --no-fetch
Note that with Git 2.10+ (Q3 2016), you can use '.
' as a branch name:
The name of the branch is recorded as
submodule.<name>.branch
in.gitmodules
forupdate --remote
.
A special value of.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
But, as commented by LubosD
With
git checkout
, if the branch name to follow is ".
", it will kill your uncommitted work!
Usegit switch
instead.
That means Git 2.23 (August 2019) or more.
See "Confused by git checkout
"
If you want to update all your submodules following a branch:
git submodule update --recursive --remote
Note that the result, for each updated submodule, will almost always be a detached HEAD, as Dan Cameron note in his answer.
(Clintm notes in the comments that, if you run git submodule update --remote
and the resulting sha1 is the same as the branch the submodule is currently on, it won't do anything and leave the submodule still "on that branch" and not in detached head state.)
To ensure the branch is actually checked out (and that won't modify the SHA1 of the special entry representing the submodule for the parent repo), he suggests:
git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git switch $branch'
Each submodule will still reference the same SHA1, but if you do make new commits, you will be able to push them because they will be referenced by the branch you want the submodule to track.
After that push within a submodule, don't forget to go back to the parent repo, add, commit and push the new SHA1 for those modified submodules.
Note the use of $toplevel
, recommended in the comments by Alexander Pogrebnyak.
$toplevel
was introduced in git1.7.2 in May 2010: commit f030c96.
it contains the absolute path of the top level directory (where
.gitmodules
is).
dtmland
adds in the comments:
The foreach script will fail to checkout submodules that are not following a branch.
However, this command gives you both:
git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; [ "$branch" = "" ] && git checkout master || git switch $branch' –
The same command but easier to read:
git submodule foreach -q --recursive \
'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
[ "$branch" = "" ] && \
git checkout master || git switch $branch' –
umläute refines dtmland's command with a simplified version in the comments:
git submodule foreach -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'
multiple lines:
git submodule foreach -q --recursive \
'git switch \
$(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'
Before Git 2.26 (Q1 2020), a fetch that is told to recursively fetch updates in submodules inevitably produces reams of output, and it becomes hard to spot error messages.
The command has been taught to enumerate submodules that had errors at the end of the operation.
See commit 0222540 (16 Jan 2020) by Emily Shaffer (nasamuffin
).
(Merged by Junio C Hamano -- gitster
-- in commit b5c71cc, 05 Feb 2020)
fetch
: emphasize failure during submodule fetchSigned-off-by: Emily Shaffer
In cases when a submodule fetch fails when there are many submodules, the error from the lone failing submodule fetch is buried under activity on the other submodules if more than one fetch fell back on
fetch-by-oid
.
Call out a failure late so the user is aware that something went wrong, and where.
Because
fetch_finish()
is only called synchronously byrun_processes_parallel,
mutexing is not required aroundsubmodules_with_errors
.
Note that, with Git 2.28 (Q3 2020), Rewrite of parts of the scripted "git submodule" Porcelain command continues; this time it is "git submodule set-branch
" subcommand's turn.
See commit 2964d6e (02 Jun 2020) by Shourya Shukla (periperidip
).
(Merged by Junio C Hamano -- gitster
-- in commit 1046282, 25 Jun 2020)
submodule
: port subcommand 'set-branch' from shell to CMentored-by: Christian Couder
Mentored-by: Kaartic Sivaraam
Helped-by: Denton Liu
Helped-by: Eric Sunshine
Helped-by: Ðoàn Tr?n Công Danh
Signed-off-by: Shourya Shukla
Convert submodule subcommand 'set-branch' to a builtin and call it via
git submodule.sh
.
Just try "Project > Clean..." - seems to be THE solution to many problems in Eclipse!
A simple way of doing this is via nargin
(N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.
It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b
and c
. Will exit if a
is not present.
function [ output_args ] = input_example( a, b, c )
if nargin < 1
error('input_example : a is a required input')
end
if nargin < 2
b = 20
end
if nargin < 3
c = 30
end
end
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
Yes, but you'll need to run it at the database level.
Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
Only for LINUX
The most simple way that I use was using proc dir, which is the container is must be running in order to inspect the docker container files.
Find out the process id (PID) of the container and store into some variable
PID=$(docker inspect -f '{{.State.Pid}}' your-container-name-here)
Make sure the container process is running, and use the variable name to get into the container folder
cd /proc/$PID/root
If you want to get through the dir without finding out the PID number, just us this long command
cd /proc/$(docker inspect -f '{{.State.Pid}}' your-container-name-here)/root
Tips:
After you get inside of the container, everything you do will affect the actual process of the container, such as stopping the service or changing the port number.
Hope it helps
Note:
This method only works if the container is still running, otherwise the directory wouldn't exist anymore if the container has stopped or removed
Some AWS services are just available in specific regions that do not match your actual region. If this is the case you can override the standard setting by adding the region to your actual cli command.
This might be a handy solution for people that do not want to change their default region in the config file. IF your general config file is not set: Please check the suggestions above.
In this example the region is forced to eu-west-1 (e.g. Ireland):
aws s3 ls --region=eu-west-1
Tested and used with aws workmail to delete users:
aws workmail delete-user --region=eu-west-1 --organization-id [org-id] --user-id [user-id]
I derived the idea from this thread and it works perfect for me - so I wanted to share it. Hope it helps!
Officially, the SQL languages does not support a JOIN or FROM clause in an UPDATE statement unless it is in a subquery. Thus, the Hoyle ANSI approach would be something like
Update addresses
Set cid = (
Select c.id
From customers As c
where c.id = a.id
)
Where Exists (
Select 1
From customers As C1
Where C1.id = addresses.id
)
However many DBMSs such Postgres support the use of a FROM clause in an UPDATE statement. In many cases, you are required to include the updating table and alias it in the FROM clause however I'm not sure about Postgres:
Update addresses
Set cid = c.id
From addresses As a
Join customers As c
On c.id = a.id
If the other solutions here do not work, make sure you are not in 'offline' mode. If enabled, android will not download the required files and you will get this error.
Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:
.flex-row-container {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
flex: 1 1 30%; /*grow | shrink | basis */_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
background-color: #fff4e6;_x000D_
border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
<div class="flex-row-item">1</div>_x000D_
<div class="flex-row-item">2</div>_x000D_
<div class="flex-row-item">3</div>_x000D_
<div class="flex-row-item">4</div>_x000D_
<div class="flex-row-item">5</div>_x000D_
<div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
Hope this helps someone else.
import array
integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]
Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.
Little bit late to the party but had some problems with getting something useful out from a ReadableStream
produced from a Odata $batch request using the Sharepoint Framework.
Had similar issues as OP, but the solution in my case was to use a different conversion method than .json()
. In my case .text()
worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.
As of Java 8, the String class has a static method join
. The first argument is a string that you want between each pair of strings, and the second is an Iterable<CharSequence>
(which are both interfaces, so something like List<String>
works. So you can just do this:
String.join(",", serverIds);
Also in Java 8, you could use the new StringJoiner
class, for scenarios where you want to start constructing the string before you have the full list of elements to put in it.
You can only do it at compile time using templates, unless you use RTTI.
It lets you use the typeid function which will yield a pointer to a type_info structure which contains information about the type.
Read up on it at Wikipedia
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
// if you need to check if all items' MyProperty doesn't have null
if (list.All(x => x.MyProperty != null))
// do something
// or if you need to check if at least one items' property has doesn't have null
if (list.Any(x => x.MyProperty != null))
// do something
But you always have to check for null
Here are the two main approaches. I prefer this one for its readability:
bar <- subset(foo, location == "there")
Note that you can string together many conditionals with &
and |
to create complex subsets.
The second is the indexing approach. You can index rows in R with either numeric, or boolean slices. foo$location == "there"
returns a vector of T
and F
values that is the same length as the rows of foo
. You can do this to return only rows where the condition returns true.
foo[foo$location == "there", ]
I found that celery purge
doesn't work for my more complex celery config. I use multiple named queues for different purposes:
$ sudo rabbitmqctl list_queues -p celery name messages consumers
Listing queues ... # Output sorted, whitespaced for readability
celery 0 2
[email protected] 0 1
[email protected] 0 1
apns 0 1
[email protected] 0 1
analytics 1 1
[email protected] 0 1
bcast.361093f1-de68-46c5-adff-d49ea8f164c0 0 1
bcast.a53632b0-c8b8-46d9-bd59-364afe9998c1 0 1
celeryev.c27b070d-b07e-4e37-9dca-dbb45d03fd54 0 1
celeryev.c66a9bed-84bd-40b0-8fe7-4e4d0c002866 0 1
celeryev.b490f71a-be1a-4cd8-ae17-06a713cc2a99 0 1
celeryev.9d023165-ab4a-42cb-86f8-90294b80bd1e 0 1
The first column is the queue name, the second is the number of messages waiting in the queue, and the third is the number of listeners for that queue. The queues are:
The analytics task is a brute force tasks that worked great on small data sets, but now takes more than 24 hours to process. Occasionally, something will go wrong and it will get stuck waiting on the database. It needs to be re-written, but until then, when it gets stuck I kill the task, empty the queue, and try again. I detect "stuckness" by looking at the message count for the analytics queue, which should be 0 (finished analytics) or 1 (waiting for last night's analytics to finish). 2 or higher is bad, and I get an email.
celery purge
offers to erase tasks from one of the broadcast queues, and I don't see an option to pick a different named queue.
Here's my process:
$ sudo /etc/init.d/celeryd stop # Wait for analytics task to be last one, Ctrl-C
$ ps -ef | grep analytics # Get the PID of the worker, not the root PID reported by celery
$ sudo kill <PID>
$ sudo /etc/init.d/celeryd stop # Confim dead
$ python manage.py celery amqp queue.purge analytics
$ sudo rabbitmqctl list_queues -p celery name messages consumers # Confirm messages is 0
$ sudo /etc/init.d/celeryd start
The second one creates a new array of Integers (first pass), and then adds all the elements of this new array to the list (second pass). It will thus be less efficient than the first one, which makes a single pass and doesn't create an unnecessary array of Integers.
A better way to use streams would be
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Which should have roughly the same performance as the first one.
Note that for such a small array, there won't be any significant difference. You should try to write correct, readable, maintainable code instead of focusing on performance.
My way
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class ReadAnnotation {
private static final Logger LOGGER = LoggerFactory.getLogger(ReadAnnotation.class);
public static boolean hasIgnoreAnnotation(String fieldName, Class entity) throws NoSuchFieldException {
return entity.getDeclaredField(fieldName).isAnnotationPresent(IgnoreAnnotation.class);
}
public static boolean isSkip(PropertyDescriptor propertyDescriptor, Class entity) {
boolean isIgnoreField;
try {
isIgnoreField = hasIgnoreAnnotation(propertyDescriptor.getName(), entity);
} catch (NoSuchFieldException e) {
LOGGER.error("Can not check IgnoreAnnotation", e);
isIgnoreField = true;
}
return isIgnoreField;
}
public void testIsSkip() throws Exception {
Class<TestClass> entity = TestClass.class;
BeanInfo beanInfo = Introspector.getBeanInfo(entity);
for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
System.out.printf("Field %s, has annotation %b", propertyDescriptor.getName(), isSkip(propertyDescriptor, entity));
}
}
}
If you have anaconda install than you just need to use command: conda install PyAudio
.
In order to execute this command you must set thePYTHONPATH
environment variable in anaconda.
JSONObject params = new JSONObject();
try {
params.put(key, val);
}catch (JSONException e){
e.printStackTrace();
}
this is how i pass "params"(JSONObject) through POST
connection.getOutputStream().write(params.toString().getBytes("UTF-8"));
It may be that your condas channels need a wakeup call... with
conda update --all
For me it worked. More information: https://www.anaconda.com/keeping-anaconda-date/
If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name
=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))
See screenshot
I use
$location.search('key', null)
As this not only deletes my key but removes it from the visibility on the URL.
Immutable and one-liner way :
const newArr = targetArr.filter(e => e !== elementToDelete);
I like to use: ArgumentException
, ArgumentNullException
, and ArgumentOutOfRangeException
.
ArgumentException
– Something is wrong with the argument.ArgumentNullException
– Argument is null.ArgumentOutOfRangeException
– I don’t use this one much, but a common use is indexing into a collection, and giving an index which is to large.There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:
InvalidOperationException
– The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.NotSupportedException
– The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.
I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.
Thanks to STW (ex Yoooder) again for the comments.
In response to your followup, I would throw an ArgumentOutOfRangeException
. Look at what MSDN says about this exception:
ArgumentOutOfRangeException
is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing
in Visual Basic) and does not contain a valid value.
So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException
, another developer might say ArgumentException
. Make it easy and document the behavior.
It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.
You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:
http://jsfiddle.net/2w157dyL/1/
However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.
So the fix is very, very simple - add enough right padding to account for the scrollbar:
http://jsfiddle.net/2w157dyL/2/
main > section {_x000D_
overflow-y: auto;_x000D_
padding-right: 2em;_x000D_
}
_x000D_
It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!
Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help
This is one example where using prepared statements really saves you some trouble.
In MySQL, in order to insert a null value, you must specify it at INSERT
time or leave the field out which requires additional branching:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', NULL);
However, if you want to insert a value in that field, you must now branch your code to add the single quotes:
INSERT INTO table2 (f1, f2)
VALUES ('String Value', 'String Value');
Prepared statements automatically do that for you. They know the difference between string(0) ""
and null
and write your query appropriately:
$stmt = $mysqli->prepare("INSERT INTO table2 (f1, f2) VALUES (?, ?)");
$stmt->bind_param('ss', $field1, $field2);
$field1 = "String Value";
$field2 = null;
$stmt->execute();
It escapes your fields for you, makes sure that you don't forget to bind a parameter. There is no reason to stay with the mysql
extension. Use mysqli
and it's prepared statements instead. You'll save yourself a world of pain.
window.fbAsyncInit = function () {_x000D_
FB.init({_x000D_
appId: 'Your-appId',_x000D_
cookie: false, // enable cookies to allow the server to access _x000D_
// the session_x000D_
xfbml: true, // parse social plugins on this page_x000D_
version: 'v2.0' // use version 2.0_x000D_
});_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
var js, fjs = d.getElementsByTagName(s)[0];_x000D_
if (d.getElementById(id)) return;_x000D_
js = d.createElement(s); js.id = id;_x000D_
js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
_x000D_
function fb_login() {_x000D_
FB.login(function (response) {_x000D_
_x000D_
if (response.authResponse) {_x000D_
console.log('Welcome! Fetching your information.... ');_x000D_
//console.log(response); // dump complete info_x000D_
access_token = response.authResponse.accessToken; //get access token_x000D_
user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
FB.api('/me', function (response) {_x000D_
var email = response.email;_x000D_
var name = response.name;_x000D_
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true); _x000D_
});_x000D_
_x000D_
} else {_x000D_
//user hit cancel button_x000D_
console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
}_x000D_
}, {_x000D_
scope: 'email'_x000D_
});_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
</fb:login-button>
_x000D_
I can't comment yet but following on Fellow Stranger solution you can also keep nesting in case you have keys which values are an array. Like this:
filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]
This works:
params.require(:model).permit(filters: [[:name, values: []]])
If the URI is not the document's location this snippet will do what you want.
var url = 'example.com/page.html#anchor',
hash = url.split('#')[1];
if (hash) {
alert(hash)
} else {
// do something else
}
You can do
display/i $pc
and every time GDB stops, it will display the disassembly of the next instruction.
GDB-7.0
also supports set disassemble-next-line on
, which will disassemble the entire next line, and give you more of the disassembly context.
Like that:
SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'
You have to drop the constraint before drop your table.
You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.
Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'
-- Find FK in This table.
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
lowercase-with-hyphens
is the style I most often see on GitHub.*
lowercase_with_underscores
is probably the second most popular style I see.
The former is my preference because it saves keystrokes.
* Anecdotal; I haven't collected any data.
Here is I would check the date format:
public static boolean checkFormat(String dateTimeString) {
return dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}") || dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}")
|| dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}") || dateTimeString
.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z") ||
dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}Z");
}
The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):
./gradlew wrapper --gradle-version 5.5
Moreover, you can use --distribution-type
parameter with either bin
or all
value to choose a distribution type. Use all
distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:
./gradlew wrapper --gradle-version 5.5 --distribution-type all
Or you can create a custom wrapper
task
task wrapper(type: Wrapper) {
gradleVersion = '5.5'
}
and run ./gradlew wrapper
.
In general, an alternative to case when ...
is coalesce(nullif(x,bad_value),y)
(that cannot be used in OP's case). For example,
select coalesce(nullif(y,''),x), coalesce(nullif(x,''),y), *
from ( (select 'abc' as x, '' as y)
union all (select 'def' as x, 'ghi' as y)
union all (select '' as x, 'jkl' as y)
union all (select null as x, 'mno' as y)
union all (select 'pqr' as x, null as y)
) q
gives:
coalesce | coalesce | x | y
----------+----------+-----+-----
abc | abc | abc |
ghi | def | def | ghi
jkl | jkl | | jkl
mno | mno | | mno
pqr | pqr | pqr |
(5 rows)
"resizeMode"
isn't style property. Should move to Image component's Props
like below code.
const win = Dimensions.get('window');
const styles = StyleSheet.create({
image: {
flex: 1,
alignSelf: 'stretch',
width: win.width,
height: win.height,
}
});
...
<Image
style={styles.image}
resizeMode={'contain'} /* <= changed */
source={require('../../../images/collection-imag2.png')} />
...
Image's height won't become automatically because Image component is required both width and height in style props
. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.
There are a lot of useful open source libraries -
I solved the simmilar problem, when i tried to push to repo via gitlab ci/cd pipeline by the command "gem install rake && bundle install"
In my case, I found out it was division by zero.
@Nat gave a good answer. But since there is no way to shorten a code, why not use contatenate to 'generate' the code you need. It works for me when I'm lazy (at typing the whole code in the cell).
So what we need is just identify the pattern > use excel to built the pattern 'structure' > add " = " and paste it in the intended cell.
For example, you want to achieve (i mean, enter in the cell) :
=IF('testsheet'!$C$1 <= 99,'testsheet'!$A$1,"") &IF('testsheet'!$C$2 <= 99,'testsheet'!$A$2,"") &IF('testsheet'!$C$3 <= 99,'testsheet'!$A$3,"") &IF('testsheet'!$C$4 <= 99,'testsheet'!$A$4,"") &IF('testsheet'!$C$5 <= 99,'testsheet'!$A$5,"") &IF('testsheet'!$C$6 <= 99,'testsheet'!$A$6,"") &IF('testsheet'!$C$7 <= 99,'testsheet'!$A$7,"") &IF('testsheet'!$C$8 <= 99,'testsheet'!$A$8,"") &IF('testsheet'!$C$9 <= 99,'testsheet'!$A$9,"") &IF('testsheet'!$C$10 <= 99,'testsheet'!$A$10,"") &IF('testsheet'!$C$11 <= 99,'testsheet'!$A$11,"") &IF('testsheet'!$C$12 <= 99,'testsheet'!$A$12,"") &IF('testsheet'!$C$13 <= 99,'testsheet'!$A$13,"") &IF('testsheet'!$C$14 <= 99,'testsheet'!$A$14,"") &IF('testsheet'!$C$15 <= 99,'testsheet'!$A$15,"") &IF('testsheet'!$C$16 <= 99,'testsheet'!$A$16,"") &IF('testsheet'!$C$17 <= 99,'testsheet'!$A$17,"") &IF('testsheet'!$C$18 <= 99,'testsheet'!$A$18,"") &IF('testsheet'!$C$19 <= 99,'testsheet'!$A$19,"") &IF('testsheet'!$C$20 <= 99,'testsheet'!$A$20,"") &IF('testsheet'!$C$21 <= 99,'testsheet'!$A$21,"") &IF('testsheet'!$C$22 <= 99,'testsheet'!$A$22,"") &IF('testsheet'!$C$23 <= 99,'testsheet'!$A$23,"") &IF('testsheet'!$C$24 <= 99,'testsheet'!$A$24,"") &IF('testsheet'!$C$25 <= 99,'testsheet'!$A$25,"") &IF('testsheet'!$C$26 <= 99,'testsheet'!$A$26,"") &IF('testsheet'!$C$27 <= 99,'testsheet'!$A$27,"") &IF('testsheet'!$C$28 <= 99,'testsheet'!$A$28,"") &IF('testsheet'!$C$29 <= 99,'testsheet'!$A$29,"") &IF('testsheet'!$C$30 <= 99,'testsheet'!$A$30,"") &IF('testsheet'!$C$31 <= 99,'testsheet'!$A$31,"") &IF('testsheet'!$C$32 <= 99,'testsheet'!$A$32,"") &IF('testsheet'!$C$33 <= 99,'testsheet'!$A$33,"") &IF('testsheet'!$C$34 <= 99,'testsheet'!$A$34,"") &IF('testsheet'!$C$35 <= 99,'testsheet'!$A$35,"") &IF('testsheet'!$C$36 <= 99,'testsheet'!$A$36,"") &IF('testsheet'!$C$37 <= 99,'testsheet'!$A$37,"") &IF('testsheet'!$C$38 <= 99,'testsheet'!$A$38,"") &IF('testsheet'!$C$39 <= 99,'testsheet'!$A$39,"") &IF('testsheet'!$C$40 <= 99,'testsheet'!$A$40,"")
I didn't type it, I just use "&" symbol to combine arranged cell in excel (another file, not the file we are working on).
Notice that :
part1 > IF('testsheet'!$C$
part2 > 1 to 40
part3 > <= 99,'testsheet'!$A$
part4 > 1 to 40
part5 > ,"") &
Now select A2:I2 , and drag it down. Notice that the number did the increament per row added, and the generated text is combined, cell by cell and line by line.
Result = code as you intended.
I've use excel/OpenOfficeCalc to help me generate code for my projects. Works for me, hope it helps for others. (:
also, you can fetch all data and count in the blade file. for example:
your code in the controller
$posts = Post::all();
return view('post', compact('posts'));
your code in the blade file.
{{ $posts->count() }}
finally, you can see the total of your posts.
The CSS below stops users from being able to select text.
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */
To target IE9 downwards the html attribute unselectable
must be used instead:
<p unselectable="on">Test Text</p>
count of the contained lists in the outmost list
int count = data.size();
lambda to get the count of the contained inner lists
int count = data.stream().collect( summingInt(l -> l.size()) );
This declaration:
double F[1000][1000000];
would occupy 8 * 1000 * 1000000 bytes on a typical x86 system. This is about 7.45 GB. Chances are your system is running out of memory when trying to execute your code, which results in a segmentation fault.
How about this:
ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest
PRIMARY KEY (wardNo, BHTNo, TestID)
UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:
see reference for the method and for UIButton
You could extend UIButton with a category to implement that method, thought.
It doesn't seem to trigger DocumentCompleted/Navigated events for external Javascript or CSS files, but it will for iframes. As PK says, compare the WebBrowserDocumentCompletedEventArgs.Url property (I don't have the karma to make a comment yet).
Add set nocount on
to the beginning of the stored proc (if you're on SQL Server). I just solved this problem in my own work and it was caused by intermediate results, such as "1203 Rows Affected"
, being loaded into the Recordset
I was trying to use.
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
$ens = $em->getRepository('AcmeBinBundle:Marks')
->findBy(
array(),
array('id' => 'ASC')
);
library
is an object, not an array. You push things onto arrays. Unlike PHP, Javascript makes a distinction.
Your code tries to make a string that looks like the source code for a key-value pair, and then "push" it onto the object. That's not even close to how it works.
What you want to do is add a new key-value pair to the object, where the key is the title and the value is another object. That looks like this:
library[title] = {"foregrounds" : foregrounds, "backgrounds" : backgrounds};
"JSON object" is a vague term. You must be careful to distinguish between an actual object in memory in your program, and a fragment of text that is in JSON format.
So you just have to do this right?:
@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul
REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls
REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls
REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul
if %input%==XD goto newecho
DEL settings.cdb
exit
:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit
just put height="400px" into image attribute like
<img class="d-block w-100" src="../assets/img/natural-backdrop.jpg" height="400px" alt="First slide">
You should try using the Grid Template.
Here's what I've used for a two Column Layout of a <ul>
<ul class="list-group row">
<li class="list-group-item col-xs-6">Row1</li>
<li class="list-group-item col-xs-6">Row2</li>
<li class="list-group-item col-xs-6">Row3</li>
<li class="list-group-item col-xs-6">Row4</li>
<li class="list-group-item col-xs-6">Row5</li>
</ul>
This worked for me.
It's a consequence of the size of the exponent part of the type, as in IEEE 754 for example. You can examine the sizes with FLT_MAX, FLT_MIN, DBL_MAX, DBL_MIN in float.h.
For those wanting a more secure way to create a random byte array, yes the most secure way is:
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
BUT your threads might block if there is not enough randomness available on the machine, depending on your OS. The following solution will not block:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
This is because the first example uses /dev/random
and will block while waiting for more randomness (generated by a mouse/keyboard and other sources). The second example uses /dev/urandom
which will not block.
If you are rounding it there is no good way to get it exactly the same in all case.
You can take the decimal part of the N percentages you have (in the example you gave it is 4).
Add the decimal parts. In your example you have total of fractional part = 3.
Ceil the 3 numbers with highest fractions and floor the rest.
(Sorry for the edits)
In PHP this did it for me (assuming the filename is UTF8 encoded):
header('Content-Disposition: attachment;'
. 'filename="' . addslashes(utf8_decode($filename)) . '";'
. 'filename*=utf-8\'\'' . rawurlencode($filename));
Tested against IE8-11, Firefox and Chrome.
If the browser can interpret filename*=utf-8 it will use the UTF8 version of the filename, else it will use the decoded filename. If your filename contains characters that can't be represented in ISO-8859-1 you might want to consider using iconv
instead.
Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp:
function AjaxFeed(){
return $.ajax({
url: 'http://somesite.com/somejsonfile.php',
data: {something: true},
dataType: 'jsonp',
/* Very important */
contentType: 'application/json',
});
}
function GetData() {
AjaxFeed()
/* Everything worked okay. Hooray */
.done(function(data){
return data;
})
/* Okay jQuery is stupid manually fix things */
.fail(function(jqXHR) {
/* Build HTML and update */
var data = jQuery.parseJSON(jqXHR.responseText);
return data;
});
}
It is still under development but you can already use jHardware
It is a simple library that scraps system data using Java. It works in both Linux and Windows.
ProcessorInfo info = HardwareInfo.getProcessorInfo();
//Get named info
System.out.println("Cache size: " + info.getCacheSize());
System.out.println("Family: " + info.getFamily());
System.out.println("Speed (Mhz): " + info.getMhz());
//[...]
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
You can simply use Python standard library. Make a shallow copy of the original image as follows:
import copy
original_img = cv2.imread("foo.jpg")
clone_img = copy.copy(original_img)
You should either remove android:configChanges="locale"
from manifest, which will cause activity to reload, or override onConfigurationChanged
method:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// your code here, you can use newConfig.locale if you need to check the language
// or just re-set all the labels to desired string resource
}
Use for...in
loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
This should work (untested, based on JavaDoc):
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US);
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);
System.out.println(formatter.format(bd.longValue()));
According to the JavaDoc, the cast in the first line should be save for most locales.
The ISO is probably pre-pidded. You'll need to delete the key from the setup files. It should then ask you for a key during installation.
Object does not have forEach
, it belongs to Array
prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};
, Object.keys(v)
gives you an array of the keys so you get ["cat","dog","bird"]
Another option is to use a destination wildcard. Note that this only works if the source and destination filenames will be the same, so while this doesn't solve the OP's specific example, I thought it was worth sharing.
For example:
xcopy /y "bin\development\whee.config.example" "TestConnectionExternal\bin\Debug\*"
will create a copy of the file "whee.config.example" in the destination directory without prompting for file or directory.
Update: As mentioned by @chapluck:
You can change "* "
to "[newFileName].*"
. It persists file extension but allows to rename. Or more hacky: "[newFileName].[newExt]*"
to change extension
For NetBeans 8+ on Windows 10 there's a definitive bug with duplicate classes error which is being solved by cleaning the cache at
C:\Users\<user>\AppData\Local\NetBeans\Cache
.
<input type="button" onclick="functionA();functionB();" />
function functionA()
{
}
function functionB()
{
}
No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)
Can't say I'm comfortable with any of the solutions based on exec. I prefer to use tee directly, so I make the script call itself with tee when requested:
# my script:
check_tee_output()
{
# copy (append) stdout and stderr to log file if TEE is unset or true
if [[ -z $TEE || "$TEE" == true ]]; then
echo '-------------------------------------------' >> log.txt
echo '***' $(date) $0 $@ >> log.txt
TEE=false $0 $@ 2>&1 | tee --append log.txt
exit $?
fi
}
check_tee_output $@
rest of my script
This allows you to do this:
your_script.sh args # tee
TEE=true your_script.sh args # tee
TEE=false your_script.sh args # don't tee
export TEE=false
your_script.sh args # tee
You can customize this, e.g. make tee=false the default instead, make TEE hold the log file instead, etc. I guess this solution is similar to jbarlow's, but simpler, maybe mine has limitations that I have not come across yet.
I'm able to exclude multiple directories using the below config (comma separated folder paths):
sonar.exclusions=system/**, test/**, application/third_party/**, application/logs/**
And while running the sonar runner I got the following in the log:
Excluded sources:
system/**
test/**
application/third_party/**
application/logs/**
shlwapi.lib/dll
uses the HKCU
registry hive internally.
It's best not to link to shlwapi.lib
if you're creating a library or the product does not have a UI. If you're writing a lib then your code can be used in any project including those that don't have UIs.
If you're writing code that runs when a user is not logged in (e.g. service [or other] set to start at boot or startup) then there's no HKCU
. Lastly, shlwapi are settlement functions; and as a result high on the list to deprecate in later versions of Windows.
After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.
The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.
Give it a try :)
*only tested in chrome so far
HTML:
<div class="frame">
<img src="image.jpg"/>
</div>
CSS:
.frame {
border: 1px solid red;
min-height: 98%;
max-height: 98%;
min-width: 99%;
max-width: 99%;
text-align: center;
margin: auto;
position: absolute;
}
img {
border: 1px solid blue;
min-height: 98%;
max-width: 99%;
max-height: 98%;
width: auto;
height: auto;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
Type t = typeof(obj1);
if (t == typeof(int))
// Some code here
This is an error. The typeof operator in C# can only take type names, not objects.
if (obj1.GetType() == typeof(int))
// Some code here
This will work, but maybe not as you would expect. For value types, as you've shown here, it's acceptable, but for reference types, it would only return true if the type was the exact same type, not something else in the inheritance hierarchy. For instance:
class Animal{}
class Dog : Animal{}
static void Foo(){
object o = new Dog();
if(o.GetType() == typeof(Animal))
Console.WriteLine("o is an animal");
Console.WriteLine("o is something else");
}
This would print "o is something else"
, because the type of o
is Dog
, not Animal
. You can make this work, however, if you use the IsAssignableFrom
method of the Type
class.
if(typeof(Animal).IsAssignableFrom(o.GetType())) // note use of tested type
Console.WriteLine("o is an animal");
This technique still leaves a major problem, though. If your variable is null, the call to GetType()
will throw a NullReferenceException. So to make it work correctly, you'd do:
if(o != null && typeof(Animal).IsAssignableFrom(o.GetType()))
Console.WriteLine("o is an animal");
With this, you have equivalent behavior of the is
keyword. Hence, if this is the behavior you want, you should use the is
keyword, which is more readable and more efficient.
if(o is Animal)
Console.WriteLine("o is an animal");
In most cases, though, the is
keyword still isn't what you really want, because it's usually not enough just to know that an object is of a certain type. Usually, you want to actually use that object as an instance of that type, which requires casting it too. And so you may find yourself writing code like this:
if(o is Animal)
((Animal)o).Speak();
But that makes the CLR check the object's type up to two times. It will check it once to satisfy the is
operator, and if o
is indeed an Animal
, we make it check again to validate the cast.
It's more efficient to do this instead:
Animal a = o as Animal;
if(a != null)
a.Speak();
The as
operator is a cast that won't throw an exception if it fails, instead returning null
. This way, the CLR checks the object's type just once, and after that, we just need to do a null check, which is more efficient.
But beware: many people fall into a trap with as
. Because it doesn't throw exceptions, some people think of it as a "safe" cast, and they use it exclusively, shunning regular casts. This leads to errors like this:
(o as Animal).Speak();
In this case, the developer is clearly assuming that o
will always be an Animal
, and as long as their assumption is correct, everything works fine. But if they're wrong, then what they end up with here is a NullReferenceException
. With a regular cast, they would have gotten an InvalidCastException
instead, which would have more correctly identified the problem.
Sometimes, this bug can be hard to find:
class Foo{
readonly Animal animal;
public Foo(object o){
animal = o as Animal;
}
public void Interact(){
animal.Speak();
}
}
This is another case where the developer is clearly expecting o
to be an Animal
every time, but this isn't obvious in the constructor, where the as
cast is used. It's not obvious until you get to the Interact
method, where the animal
field is expected to be positively assigned. In this case, not only do you end up with a misleading exception, but it isn't thrown until potentially much later than when the actual error occurred.
In summary:
If you only need to know whether or not an object is of some type, use is
.
If you need to treat an object as an instance of a certain type, but you don't know for sure that the object will be of that type, use as
and check for null
.
If you need to treat an object as an instance of a certain type, and the object is supposed to be of that type, use a regular cast.
All those answers didnt help me, BUT I found another solution.
I had an Entity A containing a List of Entity B. Entity B contained a List of Entity C.
I was trying to update Entity A and B. It worked. But when updating Entity C, I got the mentioned error. In entity B I had an annotation like this:
@OneToMany(mappedBy = "entity_b", cascade = [CascadeType.ALL] , orphanRemoval = true)
var c: List<EntityC>?,
I simply removed orphanRemoval
and the update worked.
I had same Issue and i solve it following way:
The xml file which is using for create a Row inside createViewholder, just add below line:
android:clickable="true"
android:focusableInTouchMode="true"
android:background="?attr/selectableItemBackgroundBorderless"
OR If you using frameLayout as a parent of row item then:
android:clickable="true"
android:focusableInTouchMode="true"
android:foreground="?attr/selectableItemBackgroundBorderless"
In java code inside view holder where you added on click listener:
@Override
public void onClick(View v) {
//ur other code here
v.setPressed(true);
}
Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.
Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).
Response status comes as second parameter in callback, (from docs):
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
If that's your whole string, then just try parsing it:
if (DateTime::createFromFormat('Y-m-d H:i:s', $myString) !== FALSE) {
// it's a date
}
Use the code below:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
See this bug: https://bugs.launchpad.net/ubuntu/+source/mysql-5.6/+bug/1435823
There seems to be a temporary fix there
Create a newfile /etc/tmpfiles.d/mysql.conf:
# systemd tmpfile settings for mysql
# See tmpfiles.d(5) for details
d /var/run/mysqld 0755 mysql mysql -
After reboot, mysql should start normally.
You can add days in different formats:
// Normal adding
moment().add(7, 'days');
// Short Hand
moment().add(7, 'd');
// Literal Object
moment().add({days:7, months:1});
See more about it on Moment.js docs: https://momentjs.com/docs/#/manipulating/add/
Arrays in JS have two types of properties:
Regular elements and associative properties (which are nothing but objects)
When you define a = new Array()
, you are defining an empty array. Note that there are no associative objects yet
When you define b = new Array(2)
, you are defining an array with two undefined locations.
In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.
console.log (a)
or console.log(b)
prints the array elements i.e. []
and [undefined, undefined]
respectively. But since a1/a2
and b1/b2
are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2)
kind of syntax
If you have only put (non-null) String
references in the JComboBox, then either way is fine.
However, the first solution would also allow for future modifications in which you insert Integer
s, Doubles
s, LinkedList
s etc. as items in the combo box.
To be robust against null
values (still without casting) you may consider a third option:
String x = String.valueOf(JComboBox.getSelectedItem());
For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says "Installs tkinter"
var data={
userName: $('#userName').val(),
email: $('#email').val(),
//add other properties similarly
}
and
$.ajax({
type: "POST",
url: "http://rt.ja.com/includes/register.php?submit=1",
data: data
success: function(html)
{
//alert(html);
$('#userError').html(html);
$("#userError").html(userChar);
$("#userError").html(userTaken);
}
});
You dont have to bother about anything else. jquery will handle the serialization etc. also you can append the submit query string parameter submit=1 into the data json object.
I am surprise, no one here has ans by using simple javascript
and Set
logic to automatically filter the duplicates values, simple example on mongo shellas below:
var allKeys = new Set()
db.collectionName.find().forEach( function (o) {for (key in o ) allKeys.add(key)})
for(let key of allKeys) print(key)
This will print all possible unique keys in the collection name: collectionName.
To really convert from a string to a number properly, you need to use an instance of NSNumberFormatter
configured for the locale from which you're reading the string.
Different locales will format numbers differently. For example, in some parts of the world, COMMA
is used as a decimal separator while in others it is PERIOD
— and the thousands separator (when used) is reversed. Except when it's a space. Or not present at all.
It really depends on the provenance of the input. The safest thing to do is configure an NSNumberFormatter
for the way your input is formatted and use -[NSFormatter numberFromString:]
to get an NSNumber
from it. If you want to handle conversion errors, you can use -[NSFormatter getObjectValue:forString:range:error:]
instead.
There is an extension in postgresql for this. It's name is "pg_stat_statements". https://www.postgresql.org/docs/9.4/pgstatstatements.html
Basically you have to change postgresql.conf file a little bit:
shared_preload_libraries= 'pg_stat_statements'
pg_stat_statements.track = 'all'
Then you have to log in DB and run this command:
create extension pg_stat_statements;
It will create new view with name "pg_stat_statements". In this view you can see all the executed queries.
If you are using mac-OS , export JAVA_HOME=/usr/libexec/java_home
need to be changed to export JAVA_HOME=$(/usr/libexec/java_home)
.
Steps to do this :
$ vim .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
$ source .bash_profile
where /usr/libexec/java_home
is the path of your jvm
Instead of using this in your current class setClassRoomName("aClassName");
you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.
Another way to check if FB has initialized is by using the following code:
ns.FBInitialized = function () {
return typeof (FB) != 'undefined' && window.fbAsyncInit.hasRun;
};
Thus in your page ready event you could check ns.FBInitialized and defer the event to later phase by using setTimeOut.
Sqlite helper class helps us to manage database creation and version management.
SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade()
methods of SQLiteOpenHelper
. Optionally override onOpen() method.
2.Use this subclass to create either a readable or writable database and use the SQLiteDatabase's four API methods insert(), execSQL(), update(), delete()
to create, read, update and delete rows of your table.
Example to create a MyEmployees table and to select and insert records:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "DBName";
private static final int DATABASE_VERSION = 2;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table MyEmployees
( _id integer primary key,name text not null);";
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method is called during creation of the database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
// Method is called during an upgrade of the database,
@Override
public void onUpgrade(SQLiteDatabase database,int oldVersion,int newVersion){
Log.w(MyDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS MyEmployees");
onCreate(database);
}
}
Now you can use this class as below,
public class MyDB{
private MyDatabaseHelper dbHelper;
private SQLiteDatabase database;
public final static String EMP_TABLE="MyEmployees"; // name of table
public final static String EMP_ID="_id"; // id value for employee
public final static String EMP_NAME="name"; // name of employee
/**
*
* @param context
*/
public MyDB(Context context){
dbHelper = new MyDatabaseHelper(context);
database = dbHelper.getWritableDatabase();
}
public long createRecords(String id, String name){
ContentValues values = new ContentValues();
values.put(EMP_ID, id);
values.put(EMP_NAME, name);
return database.insert(EMP_TABLE, null, values);
}
public Cursor selectRecords() {
String[] cols = new String[] {EMP_ID, EMP_NAME};
Cursor mCursor = database.query(true, EMP_TABLE,cols,null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor; // iterate to get each value.
}
}
Now you can use MyDB class in you activity to have all the database operations. The create records will help you to insert the values similarly you can have your own functions for update and delete.
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
Use Either Debug.WriteLine()
or Trace.WriteLine()
. If in release mode, only the latter will appear in the output window, in debug mode, both will.
Try This...
Go to your notification area in the taskbar.
Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.
There are several options available..
a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.
b. Disabled - It will force the portrait apps to work in landscape mode.
c. Enabled - It will force the portrait apps to work in portrait mode only.
This May help you..
@Zordid @Iambda answer is great, but I found that if I put
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
in the run() method and
mHandler.postDelayed(mUpdateUITimerTask, 0);
in the onCreate method make the thing keep updating.
Doing it the easy way, this is a function for .bash_profile, it directly unzips the archive on current location, configure first your usual [url:path]. NOTE: With this function you avoid the clone operation, it gets directly from the remote repo.
gitss() {
URL=[url:path]
TMPFILE="`/bin/tempfile`"
if [ "$1" = "" ]; then
echo -e "Use: gitss repo [tree/commit]\n"
return
fi
if [ "$2" = "" ]; then
TREEISH="HEAD"
else
TREEISH="$2"
fi
echo "Getting $1/$TREEISH..."
git archive --format=zip --remote=$URL/$1 $TREEISH > $TMPFILE && unzip $TMPFILE && echo -e "\nDone\n"
rm $TMPFILE
}
Alias for .gitconfig, same configuration required (TAKE CARE executing the command inside .git projects, it ALWAYS jumps to the base dir previously as said here, until this is fixed I personally prefer the function
ss = !env GIT_TMPFILE="`/bin/tempfile`" sh -c 'git archive --format=zip --remote=[url:path]/$1 $2 \ > $GIT_TMPFILE && unzip $GIT_TMPFILE && rm $GIT_TMPFILE' -
Yes, quite straight forward:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
In most cases, when you find yourself using forEach
on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.
Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Map
s and List
s, but no out of-the-box collector for combining two different collectors, based on a predicate.
Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as
Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
.collect(conditional(entry -> entry.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;
But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null
. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:
List<KeyType> myList=animalMap.entrySet().stream()
.filter(pair -> pair.getValue() == null)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
animalMap.keySet().removeAll(myList);
Note that you can remove mappings to null
even without having the list of the other keys:
animalMap.values().removeIf(Objects::isNull);
or
animalMap.values().removeAll(Collections.singleton(null));
If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy
is going into the right direction, but you may simplify it:
Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
.collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());
The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.
myclass.h
#ifndef __MYCLASS_H__
#define __MYCLASS_H__
class MyClass
{
public:
MyClass();
/* use virtual otherwise linker will try to perform static linkage */
virtual void DoSomething();
private:
int x;
};
#endif
myclass.cc
#include "myclass.h"
#include <iostream>
using namespace std;
extern "C" MyClass* create_object()
{
return new MyClass;
}
extern "C" void destroy_object( MyClass* object )
{
delete object;
}
MyClass::MyClass()
{
x = 20;
}
void MyClass::DoSomething()
{
cout<<x<<endl;
}
class_user.cc
#include <dlfcn.h>
#include <iostream>
#include "myclass.h"
using namespace std;
int main(int argc, char **argv)
{
/* on Linux, use "./myclass.so" */
void* handle = dlopen("myclass.so", RTLD_LAZY);
MyClass* (*create)();
void (*destroy)(MyClass*);
create = (MyClass* (*)())dlsym(handle, "create_object");
destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");
MyClass* myClass = (MyClass*)create();
myClass->DoSomething();
destroy( myClass );
}
On Mac OS X, compile with:
g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user
On Linux, compile with:
g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user
If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object
and destroy_object
. Your main application would not need to be changed in any way.
See http://angular-ui.github.io/bootstrap/#/collapse
function CollapseDemoCtrl($scope) {
$scope.isCollapsed = false;
}
<div ng-controller="CollapseDemoCtrl">
<button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
<hr>
<div collapse="isCollapsed">
<div class="well well-large">Some content</div>
</div>
</div>
I tried this and it works:
stage.getIcons().add(new Image(getClass().getResourceAsStream("../images/icon.png")));
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}
Change your second style to this:
input, select, textarea{
color: #ff0000;
}
At the moment, you are telling the form to change the text to black
once the focus is off. The above remedies that.
Also, it is a good idea to place the normal state styles ahead of the :focus
and :hover
styles in your stylesheet. That helps prevent this problem. So
input, select, textarea{
color: #ff0000;
}
textarea:focus, input:focus {
color: #ff0000;
}
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
You can simply Create a logout button and add this link to it and it will utimately log you out from the app and will redirect to your desired site:
https://appengine.google.com/_ah/logout?continue=http://www.YOURSITE.com
just toggle YOURSITE with your website
so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:
node_modules
foldernpm install --global windows-build-tools
npm install
Now a days, the easiest way I found to have a more updated version of Python is to install it via conda into a conda environment.
Install conda(you may need a virtualenv for this)
pip install conda
I'm adding this answer here because no manual download is needed. conda
will do that for you.
Now create an environment for the Python version you want. In this example I will use 3.5.2
, because it it the latest version at this time of writing (Aug 2016).
conda create -n py35 python=3.5.2
Will create a environment for conda to install packages
To activate this environment(I'm assuming linux otherwise check the conda docs):
source activate py35
Now install what you need either via pip or conda in the environemnt(conda has better binary package support).
conda install <package_name>
Sorry, but all the answers are difficult to understand for me as a beginner in graphics...
After some fiddling, this is working for me and it is easy to reason about.
@Override
public void draw(Graphics2D g) {
AffineTransform tr = new AffineTransform();
// X and Y are the coordinates of the image
tr.translate((int)getX(), (int)getY());
tr.rotate(
Math.toRadians(this.rotationAngle),
img.getWidth() / 2,
img.getHeight() / 2
);
// img is a BufferedImage instance
g.drawImage(img, tr, null);
}
I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.
This solution is an extension for a Random
class.
class Program
{
private static Random random = new Random();
static void Main(string[] args)
{
random.NextString(10); // "cH*%I\fUWH0"
random.NextString(10); // "Cw&N%27+EM"
random.NextString(10); // "0LZ}nEJ}_-"
random.NextString(); // "kFmeget80LZ}nEJ}_-"
}
}
public static class RandomEx
{
/// <summary>
/// Generates random string of printable ASCII symbols of a given length
/// </summary>
/// <param name="r">instance of the Random class</param>
/// <param name="length">length of a random string</param>
/// <returns>Random string of a given length</returns>
public static string NextString(this Random r, int length)
{
var data = new byte[length];
for (int i = 0; i < data.Length; i++)
{
// All ASCII symbols: printable and non-printable
// data[i] = (byte)r.Next(0, 128);
// Only printable ASCII
data[i] = (byte)r.Next(32, 127);
}
var encoding = new ASCIIEncoding();
return encoding.GetString(data);
}
/// <summary>
/// Generates random string of printable ASCII symbols
/// with random length of 10 to 20 chars
/// </summary>
/// <param name="r">instance of the Random class</param>
/// <returns>Random string of a random length between 10 and 20 chars</returns>
public static string NextString(this Random r)
{
int length = r.Next(10, 21);
return NextString(r, length);
}
}
Check your project's properties. On the "Application" tab, select your Program
class as the Startup object:
private void dataMain_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataMain.Columns[e.ColumnIndex].Name == "colStatus")
{
if (int.Parse(e.Value.ToString()) == 2)
{
dataMain.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.OrangeRed;
dataMain.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.White;
}
}
}
Google, as of now, cannot open w/out saving. As a workaround, I use IE Tab from the Chrome Store. It is an extension that runs IE - which does allow opening w/ out saving- inside of the Chrome browser application.
Not the best solution, but it's an effective "patch" for now.
To take an export to your local system from sql developer.
Path : C:\Source_Table_Extract\des_loan_due_dtls_src_boaf.csv
SPOOL "Path where you want to save the file"
SELECT /*csv*/ * FROM TABLE_NAME;
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
If you want to change the size of plot the use arg figsize
df.groupby(['NFF', 'ABUSE']).size().unstack()
.plot(kind='bar', stacked=True, figsize=(15, 5))
For those of us who did not see -1 by Michal Chaniewski, the complete line of code:
cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";
All above answers perfectly gives the solution to center the form using Bootstrap 4
. However, if someone wants to use out of the box Bootstrap 4
css classes without help of any additional styles and also not wanting to use flex
, we can do like this.
A sample form
HTML
<div class="container-fluid h-100 bg-light text-dark">
<div class="row justify-content-center align-items-center">
<h1>Form</h1>
</div>
<hr/>
<div class="row justify-content-center align-items-center h-100">
<div class="col col-sm-6 col-md-6 col-lg-4 col-xl-3">
<form action="">
<div class="form-group">
<select class="form-control">
<option>Option 1</option>
<option>Option 2</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" />
</div>
<div class="form-group text-center">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 1
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio">Option 2
</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="optradio" disabled>Option 3
</label>
</div>
</div>
<div class="form-group">
<div class="container">
<div class="row">
<div class="col"><button class="col-6 btn btn-secondary btn-sm float-left">Reset</button></div>
<div class="col"><button class="col-6 btn btn-primary btn-sm float-right">Submit</button></div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
Link to CodePen
https://codepen.io/anjanasilva/pen/WgLaGZ
I hope this helps someone. Thank you.
To collapse all code blocks Ctrl + Shift+ /
To expand all code blocks Ctrl + Shift+ *
pydev:
To collapse all code blocks : Ctrl + 0
To collapse all code blocks : Ctrl + 9
Is there a way to collapse all code blocks in Eclipse?
by @partizanos and @bummi
You could also disable it and at the moment that you make the submit call enable it. I think is the easiest way :)
You'd have to use WebSockets (or some similar protocol module e.g. as supported by the Flash plugin) because a normal browser application simply can't open a pure TCP socket.
The Socket.IO
module available for node.js
can help a lot, but note that it is not a pure WebSocket module in its own right.
It's actually a more generic communications module that can run on top of various other network protocols, including WebSockets, and Flash sockets.
Hence if you want to use Socket.IO
on the server end you must also use their client code and objects. You can't easily make raw WebSocket
connections to a socket.io
server as you'd have to emulate their message protocol.
Something like this:
if($('#postageyes').is(':checked')) {
// do stuff
}
You can also use a counter! It doesn't preserve the order, but it'll consider the duplicates:
>>> from collections import Counter
>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> d1, d2 = Counter(a), Counter(b)
>>> c = [n for n in d1.keys() & d2.keys() for _ in range(min(d1[n], d2[n]))]
>>> print(c)
[1,3,5]
If you have trouble resolving (like me) and you cannot delete and update the resources because you have made many changes on them, plus you are using eclipse subversive instead of native client, follow these steps:
You're done.
Padding will not work in Outlook. Instead of adding blank Image, you can simply use multiple spaces(& nbsp;) before elements/texts for padding left For padding top or bottom, you can add a div containing just spaces(& nbsp;) alone. This will work!!!