In MS Windows the temporary directory is set by the environment variable TEMP
. In XP, the temporary directory was set per-user as Local Settings\Temp.
If you change your TEMP environment variable to C:\temp
, then you get the same when you run :
System.out.println(System.getProperty("java.io.tmpdir"));
Not as nice as a single ?, but it works:
var thing = foo && foo.bar || null;
You can use as many && as you like:
var thing = foo && foo.bar && foo.bar.check && foo.bar.check.x || null;
db:create
- Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:create:all
- Creates the database for all environments.
db:drop
- Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.
db:drop:all
- Drops the database for all environments.
db:migrate
- Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.
db:migrate:redo
- Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.
db:migrate:up
- Runs the up for the given migration VERSION.
db:migrate:down
- Runs the down for the given migration VERSION.
db:migrate:status
- Displays the current migration status.
db:migrate:rollback
- Rolls back the last migration.
db:version
- Prints the current schema version.
db:forward
- Pushes the schema to the next version.
db:seed
- Runs the db/seeds.rb file.
db:schema:load
Recreates the database from the schema.rb file. Deletes existing data.
db:schema:dump
Dumps the current environment’s schema to db/schema.rb.
db:structure:load
- Recreates the database from the structure.sql file.
db:structure:dump
- Dumps the current environment’s schema to db/structure.sql.
(You can specify another file with SCHEMA=db/my_structure.sql
)
db:setup
Runs db:create, db:schema:load and db:seed.
db:reset
Runs db:drop and db:setup.
db:migrate:reset
- Runs db:drop, db:create and db:migrate.
db:test:prepare
- Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)
db:test:clone
- Recreate the test database from the current environment’s database schema.
db:test:clone_structure
- Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.
db:environment:set
- Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)
db:check_protected_environments
- Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.
Also try to dos2unix
the shell script, because sometimes it has Windows line endings and the shell does not recognize it.
$ dos2unix MigrateNshell.sh
This helps sometimes.
You basically put the files you want to commit on the command line
svn ci file1 file2 dir1/file3
command+fn+F12 is correct. Lacking of button fn the F12 is used adjust the volume.
/html/body/table/tbody/tr[9]/td[1]
In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.
The string is basically bounded from the place where it is pointed to (char *ptrChar;
), to the null character (\0
).
The char *ptrChar;
actually points to the beginning of the string (char array), and thus that is the pointer to that string,
so when you do like ptrChar[x]
for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).
These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.
The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)
I uninstalled my Node.js and showed hidden files.
Then, I went to C:\Users\yourpcname\AppData\Roaming\
and deleted the npm
and npm-cache
folders.
Finally, I installed a new version of Node.js.
DataTable dtbs = new DataTable();
DataView dvbs = new DataView(dt);
dvbs.RowFilter = "ColumnName='Filtervalue'";
dtbs = dvbs.ToTable();
You can simple use ng-init like this
<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>
To disable UAC go to Start>Control Panel>User Accounts there you will find an option Turn User Account Control on or off just click on it and uncheck User Account Control to help protect your computer click OK.
Please refer to this link : https://community.apachefriends.org/f/viewtopic.php?f=16&t=45364
As Brannon says, it's OrderByDescending
and ThenByDescending
:
var query = from person in people
orderby person.Name descending, person.Age descending
select person.Name;
is equivalent to:
var query = people.OrderByDescending(person => person.Name)
.ThenByDescending(person => person.Age)
.Select(person => person.Name);
Just googled it, and found here a handy function that is useful for converting stdClass object to array recursively.
<?php
function object_to_array($object) {
if (is_object($object)) {
return array_map(__FUNCTION__, get_object_vars($object));
} else if (is_array($object)) {
return array_map(__FUNCTION__, $object);
} else {
return $object;
}
}
?>
EDIT: I updated this answer with content from linked source (which is also changed now), thanks to mason81 for suggesting me.
I use following approach to finding memory leaks in Java. I've used jProfiler with great success, but I believe that any specialized tool with graphing capabilities (diffs are easier to analyze in graphical form) will work.
Basically analysis should start from greatest positive diff by, say, object types and find what causes those extra objects to stick in memory.
For web applications that process requests in several threads analysis gets more complicated, but nevertheless general approach still applies.
I did quite a number of projects specifically aimed at reducing memory footprint of the applications and this general approach with some application specific tweaks and trick always worked well.
You will get 6 7 printed as, as is easily tested, and here's the reason: When foo
is first called, the static variable x is initialized to 5. Then it is incremented to 6 and printed.
Now for the next call to foo
. The program skips the static variable initialization, and instead uses the value 6 which was assigned to x the last time around. The execution proceeds as normal, giving you the value 7.
Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!
$first = doubleval($_POST['first']);
$second = doubleval($_POST['second']);
if($_POST['group1'] == 'add') {
echo "$first + $second = ".($first + $second);
}
// etc
In .NET 4.0, you can use the Task Parallel Library.
In earlier versions, you can create a list of Thread
objects in a loop, calling Start
on each one, and then make another loop and call Join
on each one.
On Windows, if the debug.keystore file is not in the location (C:\Users\username\.android), the debug.keystore file may also be found in the location where you have installed Android Studio.
The following code allows you to specify the row/column number and get the resulting cell value:
WebDriver driver = new ChromeDriver();
WebElement base = driver.findElement(By.className("Table"));
tableRows = base.findElements(By.tagName("tr"));
List<WebElement> tableCols = tableRows.get([ROW_NUM]).findElements(By.tagName("td"));
String cellValue = tableCols.get([COL_NUM]).getText();
A developer recently added subtitle support to VideoView.
When the MediaPlayer
starts playing a music (or other source), it checks if there is a SubtitleController and shows this message if it's not set.
It doesn't seem to care about if the source you want to play is a music or video. Not sure why he did that.
Short answer: Don't care about this "Exception".
Edit :
Still present in Lollipop,
If MediaPlayer
is only used to play audio files and you really want to remove these errors in the logcat, the code bellow set an empty SubtitleController
to the MediaPlayer
.
It should not be used in production environment and may have some side effects.
static MediaPlayer getMediaPlayer(Context context){
MediaPlayer mediaplayer = new MediaPlayer();
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return mediaplayer;
}
try {
Class<?> cMediaTimeProvider = Class.forName( "android.media.MediaTimeProvider" );
Class<?> cSubtitleController = Class.forName( "android.media.SubtitleController" );
Class<?> iSubtitleControllerAnchor = Class.forName( "android.media.SubtitleController$Anchor" );
Class<?> iSubtitleControllerListener = Class.forName( "android.media.SubtitleController$Listener" );
Constructor constructor = cSubtitleController.getConstructor(new Class[]{Context.class, cMediaTimeProvider, iSubtitleControllerListener});
Object subtitleInstance = constructor.newInstance(context, null, null);
Field f = cSubtitleController.getDeclaredField("mHandler");
f.setAccessible(true);
try {
f.set(subtitleInstance, new Handler());
}
catch (IllegalAccessException e) {return mediaplayer;}
finally {
f.setAccessible(false);
}
Method setsubtitleanchor = mediaplayer.getClass().getMethod("setSubtitleAnchor", cSubtitleController, iSubtitleControllerAnchor);
setsubtitleanchor.invoke(mediaplayer, subtitleInstance, null);
//Log.e("", "subtitle is setted :p");
} catch (Exception e) {}
return mediaplayer;
}
This code is trying to do the following from the hidden API
SubtitleController sc = new SubtitleController(context, null, null);
sc.mHandler = new Handler();
mediaplayer.setSubtitleAnchor(sc, null)
may be in your case you could reach this with the following:
mv excluded_dir ..\
ls -R
mv ..\excluded_dir .
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
Here is another way to find out apps package name and launcher activity.
Step1: Start "adb logcat" in command prompt.
Step2: Open the app (either in emulator or real device)
Its gets even simpler (by pandas 0.16.0) :
df.columns.tolist()
will give you the column names in a nice list.
A note from Microsoft concerning SQL Server:
A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.
so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.
When referencing the PRIMARY KEY of the independent (parent) table by the similarly named column(s) in the dependent (child) table, I omit the column name(s):
FK_ChildTable_ParentTable
When referencing other columns, or the column names vary between the two tables, or just to be explicit:
FK_ChildTable_childColumn_ParentTable_parentColumn
to_frame():
Starting with the following Series, df:
email
[email protected] A
[email protected] B
[email protected] C
dtype: int64
I use to_frame to convert the series to DataFrame:
df = df.to_frame().reset_index()
email 0
0 [email protected] A
1 [email protected] B
2 [email protected] C
3 [email protected] D
Now all you need is to rename the column name and name the index column:
df = df.rename(columns= {0: 'list'})
df.index.name = 'index'
Your DataFrame is ready for further analysis.
Update: I just came across this link where the answers are surprisingly similar to mine here.
I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..
Deprecated means they don't recommend using it, and that it isn't undergoing further development. But it should not work differently than it did in a previous version unless documentation explicitly states that.
Yes, otherwise it wouldn't be called "deprecated"
Unless stated otherwise in docs, it should be the same as before
No, but if there were problems in v1 they aren't about to fix them
In some cases you can pipe after the command a Out-Null
command | Out-Null
You can use basename()
and $_SERVER['PHP_SELF']
to get current page file name
echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */
I change upload method with images[]
according to @Denmark.
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}
you can try
isfar <- get(load('c:/users/isfar.Rdata'))
this will assign the variable in isfar.Rdata to isfar . After this assignment, you can use str(isfar) or ls(isfar) or head(isfar) to get a rough look of the isfar.
As an extension to @JBNizet's answer for more technical users here's what implementation of org.w3c.dom.Node
interface in com.sun.org.apache.xerces.internal.dom.ParentNode
looks like, gives you the idea how it actually works.
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid;
for (kid = firstChild; kid != null; kid = kid.nextSibling) {
kid.normalize();
}
isNormalized(true);
}
It traverses all the nodes recursively and calls kid.normalize()
This mechanism is overridden in org.apache.xerces.dom.ElementImpl
public void normalize() {
// No need to normalize if already normalized.
if (isNormalized()) {
return;
}
if (needsSyncChildren()) {
synchronizeChildren();
}
ChildNode kid, next;
for (kid = firstChild; kid != null; kid = next) {
next = kid.nextSibling;
// If kid is a text node, we need to check for one of two
// conditions:
// 1) There is an adjacent text node
// 2) There is no adjacent text node, but kid is
// an empty text node.
if ( kid.getNodeType() == Node.TEXT_NODE )
{
// If an adjacent text node, merge it with kid
if ( next!=null && next.getNodeType() == Node.TEXT_NODE )
{
((Text)kid).appendData(next.getNodeValue());
removeChild( next );
next = kid; // Don't advance; there might be another.
}
else
{
// If kid is empty, remove it
if ( kid.getNodeValue() == null || kid.getNodeValue().length() == 0 ) {
removeChild( kid );
}
}
}
// Otherwise it might be an Element, which is handled recursively
else if (kid.getNodeType() == Node.ELEMENT_NODE) {
kid.normalize();
}
}
// We must also normalize all of the attributes
if ( attributes!=null )
{
for( int i=0; i<attributes.getLength(); ++i )
{
Node attr = attributes.item(i);
attr.normalize();
}
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
isNormalized(true);
}
Hope this saves you some time.
<a href="#" class="btn btn-default" id="btnforvideo" data-toggle="modal" data-target="#videoModal">VIDEO</a>
<div class="modal fade" id="videoModal" tabindex="-1" role="dialog" aria-labelledby="videoModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div>
<iframe width="100%" height="315" src="https://www.youtube.com/embed/myvideocode" frameborder="0" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</div>
#include<stdio.h>
int main ( ) {
printf( "hello " );
fprintf( stderr, "HELP!" );
printf( " world\n" );
return 0;
}
$ ./a.exe
HELP!hello world
$ ./a.exe 2> tmp1
hello world
$ ./a.exe 1> tmp1
HELP!$
stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.
Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.
A simple program to print "N" prime numbers. You can use N value as 100.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
I've found this solution by googling. I have just had this problem and it solved it.
My mistake was to put a project in other location out of the workspace, and share this workspace between several computers, where the paths difer. I learned that, when a project is out of workspace, its location is saved in workspace/.metadata/.plugins/org.eclipse.core.resources/.projects/PROJECTNAME/.location
Deleting .location and reimporting the project into workspace solved the issue. Hope this helps.
I used something that resembles singleton pattern:
function myclass() = {
var instance = this;
this.Days = function() {
var days = ["Piatek", "Sobota", "Niedziela"];
return days;
}
this.EventTime = function(day, hours, minutes) {
this.Day = instance.Days()[day];
this.Hours = hours;
this.minutes = minutes;
this.TotalMinutes = day*24*60 + 60*hours + minutes;
}
}
Solution for LAMP users:
apt-get install php5-json
service apache2 restart
Moved my comment into an answer per suggestion above:
You don't need extra packages, here's a one-liner:
d <- cbind(rownames(d), data.frame(d, row.names=NULL))
Run this convenient SQL query to see running MySQL queries. It can be run from any environment you like, whenever you like, without any code changes or overheads. It may require some MySQL permissions configuration, but for me it just runs without any special setup.
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep';
The only catch is that you often miss queries which execute very quickly, so it is most useful for longer-running queries or when the MySQL server has queries which are backing up - in my experience this is exactly the time when I want to view "live" queries.
You can also add conditions to make it more specific just any SQL query.
e.g. Shows all queries running for 5 seconds or more:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND TIME >= 5;
e.g. Show all running UPDATEs:
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST WHERE COMMAND != 'Sleep' AND INFO LIKE '%UPDATE %';
For full details see: http://dev.mysql.com/doc/refman/5.1/en/processlist-table.html
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Well I think firstly keep whole main into try catch(or you can use as public static void main(String arg[]) throws IOException )
and then also use full path of file in which you are writing as
PrintWriter printWriter = new PrintWriter ("C:/Users/Me/Desktop/directory/file.txt");
all those directies like users,Me,Desktop,directory should be user made. java wont make directories own its own. it should be as
import java.io.*;
public class PrintWriterClass {
public static void main(String arg[]) throws IOException{
PrintWriter pw = new PrintWriter("C:/Users/Me/Desktop/directory/file.txt");
pw.println("hiiiiiii");
pw.close();
}
}
Using standard JSF API, add the client ID to PartialViewContext#getRenderIds()
.
FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add("foo:bar");
Using PrimeFaces specific API, use PrimeFaces.Ajax#update()
.
PrimeFaces.current().ajax().update("foo:bar");
Or if you're not on PrimeFaces 6.2+ yet, use RequestContext#update()
.
RequestContext.getCurrentInstance().update("foo:bar");
If you happen to use JSF utility library OmniFaces, use Ajax#update()
.
Ajax.update("foo:bar");
Regardless of the way, note that those client IDs should represent absolute client IDs which are not prefixed with the NamingContainer
separator character like as you would do from the view side on.
My simple solution. IMHO it's the cleanest.
First create a application.yml
spring.main.allow-bean-definition-overriding: true
security:
oauth2:
client:
clientId: XXX
clientSecret: XXX
accessTokenUri: XXX
tokenName: access_token
grant-type: client_credentials
Create the main class: Main
@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll();
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
@Bean
public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
return new OAuth2RestTemplate(details);
}
}
Then Create the controller class: Controller
@RestController
class OfferController {
@Autowired
private OAuth2RestOperations restOperations;
@RequestMapping(value = "/<your url>"
, method = RequestMethod.GET
, produces = "application/json")
public String foo() {
ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
return responseEntity.getBody();
}
}
Maven dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
</dependencies>
this works
import tkinter as tk
inputEdit.delete("1.0",tk.END)
Building on @sreedeep-kesav's answer (not enough rep to comment), Privacy - Camera Usage Description
and Privacy - Photo Library Usage Description
can be set by opening your Info.plist
file in Xcode and selecting the plus button next to Information Property List
:
<div class="outer">
<div class="inner">
<img src="http://1.bp.blogspot.com/_74so2YIdYpM/TEd09Hqrm6I/AAAAAAAAApY/rwGCm5_Tawg/s320/tall+copy.jpg" alt="tall image" />
</div>
</div>
<hr />
<div class="outer">
<div class="inner">
<img src="http://www.5150studios.com.au/wp-content/uploads/2012/04/wide.jpg" alt="wide image" />
</div>
</div>
CSS
img
{
max-width: 100%;
max-height: 100%;
display: block;
margin: auto auto;
}
.outer
{
border: 1px solid #888;
width: 100px;
height: 100px;
}
.inner
{
display:table-cell;
height: 100px;
width: 100px;
vertical-align: middle;
}
The ExecuteScalar method should be used when you are really sure your query returns only one value like below:
SELECT ID FROM USERS WHERE USERNAME = 'SOMENAME'
If you want the whole row then the below code should more appropriate.
SqlCommand check_User_Name = new SqlCommand("SELECT * FROM Table WHERE ([user] = @user)" , conn);
check_User_Name.Parameters.AddWithValue("@user", txtBox_UserName.Text);
SqlDataReader reader = check_User_Name.ExecuteReader();
if(reader.HasRows)
{
//User Exists
}
else
{
//User NOT Exists
}
( If your url is correct and still get that error messege ) Do following steps to setup the Classpath in netbeans,
Now you will see that .jar file will be included under the libraries. Now you will not need to use the line, Class.forName("com.mysql.jdbc.Driver"); also.
If above method did not work, check the mysql-connector version (eg:- 5.1.35) and try a newer or a suitable version for you.
We use object-scan for most of our data processing. It's conceptually very simple, but allows for a lot of cool stuff. Here is how you would solve your question
// const objectScan = require('object-scan');
const findDinner = (dinner, data) => objectScan(['*'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.dinner === dinner
})(data);
const data = { 1: { name: 'bob', dinner: 'pizza' }, 2: { name: 'john', dinner: 'sushi' }, 3: { name: 'larry', dinner: 'hummus' } };
console.log(findDinner('sushi', data));
// => { name: 'john', dinner: 'sushi' }
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
UPDATE t1
LEFT JOIN
t2
ON t2.id = t1.id
SET t1.col1 = newvalue
WHERE t2.id IS NULL
Note that for a SELECT
it would be more efficient to use NOT IN
/ NOT EXISTS
syntax:
SELECT t1.*
FROM t1
WHERE t1.id NOT IN
(
SELECT id
FROM t2
)
See the article in my blog for performance details:
LEFT JOIN
compared to NOT IN
Unfortunately, MySQL
does not allow using the target table in a subquery in an UPDATE
statement, that's why you'll need to stick to less efficient LEFT JOIN
syntax.
If you add JDK_PATH in gradle.properties your build become dependent on on that particular path. Instead Run gradle task with following command line parametemer
gradle build -Dorg.gradle.java.home=/JDK_PATH
This way your build is not dependent on some concrete path.
A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
The most commonly used type parameter names are:
In Java 7 it is permitted to instantiate like this:
Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6
I was looking to do the same thing. problem for me was my url was getting way too long. I found a solution today using Bruno Jouhier's jsUrl.js library.
I haven't tested it very thoroughly yet. However, here is an example showing character lengths of the string output after encoding the same large object using 3 different methods:
jQuery.param
JSON.stringify + encodeURIComponent
JSURL.stringify
clearly JSURL has the most optimized format for urlEncoding a js object.
the thread at https://groups.google.com/forum/?fromgroups=#!topic/nodejs/ivdZuGCF86Q shows benchmarks for encoding and parsing.
Note: After testing, it looks like jsurl.js library uses ECMAScript 5 functions such as Object.keys, Array.map, and Array.filter. Therefore, it will only work on modern browsers (no ie 8 and under). However, are polyfills for these functions that would make it compatible with more browsers.
Adding to the correct answers above, the problem still might occur due to library nesting. In this case, try as the example below:
compile 'com.android.support:support-v4:20.+'
compile ('com.github.chrisbanes.actionbarpulltorefresh:extra-abs:+') { // example
exclude group: 'com.android.support', module:'support-v4'
exclude group: 'com.android.support', module:'appcompat-v7'
}
There are two points I want to make about yield here. First, while a lot of answers here talk about different ways to pass a block to a method which uses yield, let's also talk about the control flow. This is especially relevant since you can yield MULTIPLE times to a block. Let's take a look at an example:
class Fruit
attr_accessor :kinds
def initialize
@kinds = %w(orange apple pear banana)
end
def each
puts 'inside each'
3.times { yield (@kinds.tap {|kinds| puts "selecting from #{kinds}"} ).sample }
end
end
f = Fruit.new
f.each do |kind|
puts 'inside block'
end
=> inside each
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
=> selecting from ["orange", "apple", "pear", "banana"]
=> inside block
When the each method is invoked, it executes line by line. Now when we get to the 3.times block, this block will be invoked 3 times. Each time it invokes yield. That yield is linked to the block associated with the method that called the each method. It is important to notice that each time yield is invoked, it returns control back to the block of the each method in client code. Once the block is finished executing, it returns back to the 3.times block. And this happens 3 times. So that block in client code is invoked on 3 separate occasions since yield is explicitly called 3 separate times.
My second point is about enum_for and yield. enum_for instantiates the Enumerator class and this Enumerator object also responds to yield.
class Fruit
def initialize
@kinds = %w(orange apple)
end
def kinds
yield @kinds.shift
yield @kinds.shift
end
end
f = Fruit.new
enum = f.to_enum(:kinds)
enum.next
=> "orange"
enum.next
=> "apple"
So notice every time we invoke kinds with the external iterator, it will invoke yield only once. The next time we call it, it will invoke the next yield and so on.
There's an interesting tidbit with regards to enum_for. The documentation online states the following:
enum_for(method = :each, *args) ? enum
Creates a new Enumerator which will enumerate by calling method on obj, passing args if any.
str = "xyz"
enum = str.enum_for(:each_byte)
enum.each { |b| puts b }
# => 120
# => 121
# => 122
If you do not specify a symbol as an argument to enum_for, ruby will hook the enumerator to the receiver's each method. Some classes do not have an each method, like the String class.
str = "I like fruit"
enum = str.to_enum
enum.next
=> NoMethodError: undefined method `each' for "I like fruit":String
Thus, in the case of some objects invoked with enum_for, you must be explicit as to what your enumerating method will be.
I just went through this myself and found the solution. See an ASP.NET label server control actually gets redered as a span (not an input), so using the .val() property to get/set will not work. Instead you must use the 'text' property on the span in conjuntion with using the controls .ClientID property. The following code will work:
$("#<%=lblVessel.ClientID %>").text('NewText');
If this is all the object is going to store, then best literal would be
var top_brands = {
'Adidas' : 100,
'Nike' : 50
};
Then all you need is a for...in
loop.
for (var key in top_brands){
console.log(key, top_brands[key]);
}
Example.
This runs on cscript.exe, on windows.
// define the Car class
(function() {
// makeClass - By John Resig (MIT Licensed)
// Allows either new User() or User() to be employed for construction.
function makeClass(){
return function(args){
if ( this instanceof arguments.callee ) {
if ( typeof this.init == "function" )
this.init.apply( this, (args && args.callee) ? args : arguments );
} else
return new arguments.callee( arguments );
};
}
Car = makeClass();
Car.prototype.init = function(make, model, price, topSpeed, weight) {
this.make = make;
this.model = model;
this.price = price;
this.weight = weight;
this.topSpeed = topSpeed;
};
})();
// create a list of cars
var autos = [
new Car("Chevy", "Corvair", 1800, 88, 2900),
new Car("Buick", "LeSabre", 31000, 138, 3700),
new Car("Toyota", "Prius", 24000, 103, 3200),
new Car("Porsche", "911", 92000, 155, 3100),
new Car("Mercedes", "E500", 67000, 145, 3800),
new Car("VW", "Passat", 31000, 135, 3700)
];
// a list of sorting functions
var sorters = {
byWeight : function(a,b) {
return (a.weight - b.weight);
},
bySpeed : function(a,b) {
return (a.topSpeed - b.topSpeed);
},
byPrice : function(a,b) {
return (a.price - b.price);
},
byModelName : function(a,b) {
return ((a.model < b.model) ? -1 : ((a.model > b.model) ? 1 : 0));
},
byMake : function(a,b) {
return ((a.make < b.make) ? -1 : ((a.make > b.make) ? 1 : 0));
}
};
function say(s) {WScript.Echo(s);}
function show(title)
{
say ("sorted by: "+title);
for (var i=0; i < autos.length; i++) {
say(" " + autos[i].model);
}
say(" ");
}
autos.sort(sorters.byWeight);
show("Weight");
autos.sort(sorters.byModelName);
show("Name");
autos.sort(sorters.byPrice);
show("Price");
You can also make a general sorter.
var byProperty = function(prop) {
return function(a,b) {
if (typeof a[prop] == "number") {
return (a[prop] - b[prop]);
} else {
return ((a[prop] < b[prop]) ? -1 : ((a[prop] > b[prop]) ? 1 : 0));
}
};
};
autos.sort(byProperty("topSpeed"));
show("Top Speed");
It should be pretty obvious from your question that you're actually just asking about the difference between git merge
and git rebase
.
So let's suppose you're in the common case - you've done some work on your master branch, and you pull from origin's, which also has done some work. After the fetch, things look like this:
- o - o - o - H - A - B - C (master)
\
P - Q - R (origin/master)
If you merge at this point (the default behavior of git pull), assuming there aren't any conflicts, you end up with this:
- o - o - o - H - A - B - C - X (master)
\ /
P - Q - R --- (origin/master)
If on the other hand you did the appropriate rebase, you'd end up with this:
- o - o - o - H - P - Q - R - A' - B' - C' (master)
|
(origin/master)
The content of your work tree should end up the same in both cases; you've just created a different history leading up to it. The rebase rewrites your history, making it look as if you had committed on top of origin's new master branch (R
), instead of where you originally committed (H
). You should never use the rebase approach if someone else has already pulled from your master branch.
Finally, note that you can actually set up git pull
for a given branch to use rebase instead of merge by setting the config parameter branch.<name>.rebase
to true. You can also do this for a single pull using git pull --rebase
.
df.drop(labels=df[df.index % 3 != 0].index, axis=0) # every 3rd row (mod 3)
I would rather use Last()
from LINQ to do it.
rows = rows.Remove(rows.Last());
or
rows = rows.Remove(rows.LastOrDefault());
If you are running Linux, the following command is really useful for this:
trickle -s -d 50 -w 100 firefox
The -s
tells the command to run standalone, the -d 50
tells it to limit bandwidth to 50 KB/s, the -w 100
set the peak detection window size to 100 KB. firefox
tells the command to start firefox with all of this rate limiting applied to any sites it attempts to load.
Update
Chrome 38 is out now and includes throttling. To find it, bring up the Developer Tools: Ctrl+Shift+I does it on my machine, otherwise Menu->More Tools->Developer Tools will bring you there.
Then Toggle Device Mode by clicking the phone in the upper left of the Developer Tools Panel (see the tooltip below).
Then activate throttling like so.
If you find this a bit clunky, my suggestion above works for both Chrome and Firefox.
It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.
To change current working dir to the one containing your script you can use:
import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())
The __file__
variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?
I have found the IIS Log files at the following location.
C:\inetpub\logs\LogFiles\
which help to fix my issue.
Using VS2013 .net 4.5
I had this same issue.
The "Most likely causes" section on the error message page provided the most help. For me. It said "This application defines configuration in the system.web/httpModules section." Then in the "Things you can try" section it said "Migrate the configuration to the system.webServer/modules section."
<system.web>
<httpHandlers>
<add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" validate="false" />
<add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" validate="false" />
</httpHandlers>
<httpModules>
<add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</httpModules>
</system.web>
into the system.webServer section.
<system.webServer>
<handlers>
<add type="DevExpress.Web.ASPxUploadProgressHttpHandler, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET,POST" path="ASPxUploadProgressHandlerPage.ashx" name="ASPxUploadProgressHandler" preCondition="integratedMode" />
<add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" verb="GET" path="DX.ashx" name="ASPxHttpHandlerModule" preCondition="integratedMode" />
</handlers>
<modules>
<add type="DevExpress.Web.ASPxHttpHandlerModule, DevExpress.Web.v15.1, Version=15.1.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" name="ASPxHttpHandlerModule" />
</modules>
</system.webServer>
[UPDATED privacy keys list to iOS 13 - see below]
There is a list of all Cocoa Keys
that you can specify in your Info.plist
file:
(Xcode: Target -> Info -> Custom iOS Target Properties)
iOS already required permissions to access microphone, camera, and media library earlier (iOS 6, iOS 7), but since iOS 10 app will crash if you don't provide the description why you are asking for the permission (it can't be empty).
Privacy keys with example description:
Alternatively, you can open Info.plist
as source code:
And add privacy keys like this:
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} always location use</string>
List of all privacy keys: [UPDATED to iOS 13]
NFCReaderUsageDescription
NSAppleMusicUsageDescription
NSBluetoothAlwaysUsageDescription
NSBluetoothPeripheralUsageDescription
NSCalendarsUsageDescription
NSCameraUsageDescription
NSContactsUsageDescription
NSFaceIDUsageDescription
NSHealthShareUsageDescription
NSHealthUpdateUsageDescription
NSHomeKitUsageDescription
NSLocationAlwaysUsageDescription
NSLocationUsageDescription
NSLocationWhenInUseUsageDescription
NSMicrophoneUsageDescription
NSMotionUsageDescription
NSPhotoLibraryAddUsageDescription
NSPhotoLibraryUsageDescription
NSRemindersUsageDescription
NSSiriUsageDescription
NSSpeechRecognitionUsageDescription
NSVideoSubscriberAccountUsageDescription
In the last months, two of my apps were rejected during the review because the camera usage description wasn't specifying what I do with taken photos.
I had to change the description from ${PRODUCT_NAME} need access to the camera to take a photo
to ${PRODUCT_NAME} need access to the camera to update your avatar
even though the app context was obvious (user tapped on the avatar).
It seems that Apple is now paying even more attention to the privacy usage descriptions, and we should explain in details why we are asking for permission.
try this to get the box-shadow under your full control.
<html>
<head>
<style>
div {
width:300px;
height:100px;
background-color:yellow;
box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
}
</style>
</head>
<body>
<div>
</div>
</body>
</html>
this would apply to outer box-shadow as well.
HTTP Is the Protocol handling the transmission of data over the internet.
If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.
The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.
HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says 200 OK
.
i.e : I've completed my job of getting it to you, the rest is up to you.
I know this has been answered already but I put it in words I can understand. sorry for any repetition.
You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect
session (note that options 1-4 will also work when you're not doing a bisect):
git show
.git log -1
.git status
.git bisect visualize
.I'll explain each option in detail below.
As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect
), you can use git show
with the -s
option to suppress patch output:
$ git show --oneline -s
a9874fd Merge branch 'epic-feature'
You can also simply do git log -1
to find out which commit you're currently on.
$ git log -1 --oneline
c1abcde Add feature-003
In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde
checked out:
# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $
# Prompt at detached HEAD state
user ~ (c1abcde...) $
Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status
will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:
$ git status
# HEAD detached at c1abcde <== RIGHT HERE
Finally, while you're doing a git bisect
, you can also simply use git bisect visualize
or its built-in alias git bisect view
to launch gitk
, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:
git bisect visualize
git bisect view # shorter, means same thing
I'm using this to redirect with React Router v4:
this.props.history.push('/foo');
Hope it work for you ;)
In Chart.js version 2.0 this is possible:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See axes labelling documentation for more details.
You can serve PHP directly with node WAS: https://github.com/paragi/was
If you do gridview.bind()
at:
if(!IsPostBack)
{
//your gridview bind code here...
}
Then you can use DataTable dt = Gridview1.DataSource as DataTable;
in function to retrieve datatable.
But I bind the datatable to gridview when i click button, and recording to Microsoft document:
HTTP is a stateless protocol. This means that a Web server treats each HTTP request for a page as an independent request. The server retains no knowledge of variable values that were used during previous requests.
If you have same condition, then i will recommend you to use Session
to persist the value.
Session["oldData"]=Gridview1.DataSource;
After that you can recall the value when the page postback again.
DataTable dt=(DataTable)Session["oldData"];
References: https://msdn.microsoft.com/en-us/library/ms178581(v=vs.110).aspx#Anchor_0
https://www.c-sharpcorner.com/UploadFile/225740/introduction-of-session-in-Asp-Net/
Stop MongoDB
Stop the mongod process by issuing the following command:
sudo service mongod stop
Remove Packages
Remove any MongoDB packages that you had previously installed.
sudo apt-get purge mongodb-org*
Remove Data Directories.
Remove MongoDB databases and log files.
sudo rm -r /var/log/mongodb /var/lib/mongodb
There are two way that you can add two number in jQuery
First way:
var x = parseInt(a) + parseInt(b);
alert(x);
Second Way:
var x = parseInt(a+2);
alert(x);
Now come your question
var a = parseInt($("#a").val());
var b = parseInt($("#b").val());
alert(a+b);
No, there isn't an equivalent. The <iframe>
element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage
method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe
stays as a good way to do.
In general, to make sure something happens no matter what, you use
from exceptions import NameError
try:
f = open(x)
except ErrorType as e:
pass # handle the error
finally:
try:
f.close()
except NameError: pass
finally
blocks will be run whether or not there is an error in the try
block, and whether or not there is an error in any error handling that takes place in except
blocks. If you don't handle an exception that is raised, it will still be raised after the finally
block is excecuted.
The general way to make sure a file is closed is to use a "context manager".
http://docs.python.org/reference/datamodel.html#context-managers
with open(x) as f:
# do stuff
This will automatically close f
.
For your question #2, bar
gets closed on immediately when it's reference count reaches zero, so on del foo
if there are no other references.
Objects are NOT created by __init__
, they're created by __new__
.
http://docs.python.org/reference/datamodel.html#object.new
When you do foo = Foo()
two things are actually happening, first a new object is being created, __new__
, then it is being initialized, __init__
. So there is no way you could possibly call del foo
before both those steps have taken place. However, if there is an error in __init__
, __del__
will still be called because the object was actually already created in __new__
.
Edit: Corrected when deletion happens if a reference count decreases to zero.
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
If you are reading the dataframe from a file (say CSV or Excel) then use :
df.read_csv(path , na_filter=False)
df.read_excel(path , na_filter=False)
This will automatically consider the empty fields as empty strings ''
If you already have the dataframe
df = df.replace(np.nan, '', regex=True)
df = df.fillna('')
"There are no safe means of assigning multiple recipients to a single mailto: link via HTML. There are safe, non-HTML, ways of assigning multiple recipients from a mailto: link."
http://www.sightspecific.com/~mosh/www_faq/multrec.html
For a quick fix to your problem, change your ;
to a comma ,
and eliminate the spaces between email addresses
<a href='mailto:[email protected],[email protected]'>Email Us</a>
For most controls, you set its height and width to Auto
in the XAML, and it will size to fit its content.
In code, you set the width/height to double.NaN
. For details, see FrameworkElement.Width, particularly the "remarks" section.
In anaconda envirement through windows the commands should be: GET, for ex:
curl.exe http://127.0.0.1:5000/books
Post or Patch the data for ex:
curl.exe http://127.0.0.1:5000/books/8 -X PATCH -H "Content-Type: application/json" -d '{\"rating\":\"2\"}'
PS: Add backslash for json data to avoid this type of error => Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
and use curl.exe
instead of curl
only to avoid this problem:
Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Content-Type: application/json" value of type
"System.String" to type "System.Collections.IDictionary".
At line:1 char:48
+ ... 0.1:5000/books/8 -X PATCH -H "Content-Type: application/json" -d '{\" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I believe you're looking for MySQL's LAST_INSERT_ID() function. If in the command line, simply run the following:
LAST_INSERT_ID();
You could also obtain this value through a SELECT query:
SELECT LAST_INSERT_ID();
That's a side-effect of a feature called optimistic concurrency.
Not 100% sure how to turn it on/off in Entity Framework but basically what it's telling you is that between when you grabbed the data out of the database and when you saved your changes someone else has changed the data (Which meant when you went to save it 0 rows actually got updated). In SQL terms, their update
query's where
clause contains the original value of every field in the row, and if 0 rows are affected it knows something's gone wrong.
The idea behind it is that you won't end up overwriting a change that your application didn't know has happened - it's basically a little safety measure thrown in by .NET on all your updates.
If it's consistent, odds are it's happening within your own logic (EG: You're actually updating the data yourself in another method in-between the select and the update), but it could be simply a race condition between two applications.
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Take a look at permatswap()
in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.
mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
This gives:
R> out$perm[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 1
[2,] 0 1 0 1 0
[3,] 0 0 0 1 1
[4,] 1 0 0 0 1
R> out$perm[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 0 1 1
[2,] 0 0 0 1 1
[3,] 1 0 0 1 0
[4,] 0 0 1 0 1
To explain the call:
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
times
is the number of randomised matrices you want, here 99burnin
is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matricesthin
says only take a random draw every thin
swapsmtype = "prab"
says treat the matrix as presence/absence, i.e. binary 0/1 data.A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin
is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.
Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.
This may also be achieved using matplotlib.pyplot.quiver
, as noted in the linked answer;
plt.quiver([0, 0, 0], [0, 0, 0], [1, -2, 4], [1, 2, -7], angles='xy', scale_units='xy', scale=1)
plt.xlim(-10, 10)
plt.ylim(-10, 10)
plt.show()
function wp_get_post_categories( $post_id = 0, $args = array() )
{
$post_id = (int) $post_id;
$defaults = array('fields' => 'ids');
$args = wp_parse_args( $args, $defaults );
$cats = wp_get_object_terms($post_id, 'category', $args);
return $cats;
}
Here is the second argument of function wp_get_post_categories()
which you can pass the attributes of receiving data.
$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
echo $cd->name;
}
Try this
Here is the old DEMO:
EDIT: (Here is a working DEMO with Bootstrap 3 and jQuery 1.8.3)
$(document).ready(function() {
$('#modal-content').modal('show');
$('#modal-content').on('shown', function() {
$("#txtname").focus();
})
});
Starting bootstrap 3 need to use shown.bs.modal event:
$('#modal-content').on('shown.bs.modal', function() {
$("#txtname").focus();
})
Also, you can use or create and share Visual Studio color schemes: https://studiostyl.es/
In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code
<Grid>
<Grid.Background>
<ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
AlignmentY="Top" AlignmentX="Center"/>
</Grid.Background>
</Grid>
Update A recent comment claims this doesn't work in the new Chrome ... As shown in jsFiddle, and tested on my personal site, this method still works as of Chrome ver 26.0.1410.64 m
This is REALLY easy in jQuery by the way:
// slight update to account for browsers not supporting e.which
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
// To disable f5
/* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);
// To re-enable f5
/* jQuery < 1.7 */
$(document).unbind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).off("keydown", disableF5);
On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes. Can't say I really know how to do this as I haven't done it yet.
On the software site that I work at, we use my disableF5 function in conjunction with Codeigniter's session data. For instance, there is a lock button which will lock the screen and prompt a password dialog. The function "disableF5" is quick and easy and keeps that button from doing anything. However, to prevent the mouse-click on refresh button, a couple things take place.
TIP: Try using a server-set cookie, such as PHP's $_SESSION
, or even .Net's Response.Cookies
, to maintain "where" your client is in your site. This is the more Vanilla way to do what I do with CI's Session class. The big difference being that CI uses a Table in your DB, whereas these vanilla methods store an editable cookie in the client. The downside though, is a user can clear its cookies.
Two things you should have for fetch = FetchType.LAZY
.
@Transactional
and
Hibernate.initialize(topicById.getComments());
your exists syntax is wrong and you should seperate DDL with go like below
if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go
create view tst
as
select * from test
you also can check existence test, with object_id like below
if object_id('tst','v') is not null
drop view tst;
go
create view tst
as
select * from test
In SQL 2016,you can use below syntax to drop
Drop view if exists dbo.tst
From SQL2016 CU1,you can do below
create or alter view vwTest
as
select 1 as col;
go
The error you receive is from another method than the one you show here. It's a method that takes a parameter with the name "source". In your Visual Studio Options dialog, disable "Just my code", disable "Step over properties and operators" and enable "Enable .NET Framework source stepping". Make sure the .NET symbols can be found. Then the debugger will break inside the .NET method if it isn't your own. then check the stacktrace to find which value is passed that's null, but shouldn't.
What you should look for is a value that becomes null
and prevent that. From looking at your code, it may be the itemsal.Add
line that breaks.
Since you seem to have trouble with debugging in general and LINQ especially, let's try to help you out step by step (also note the expanded first section above if you still want to try it the classic way, I wasn't complete the first time around):
null
with something deliberately not null
;First make the code a bit more readable by splitting it in manageable pieces:
// in your using-section, add this:
using Roundsman.BAL;
// keep this in your normal location
var nCounts = from sale in sal
select new
{
SaleID = sale.OrderID,
LineItem = GetLineItem(sale.LineItems)
};
foreach (var item in nCounts)
{
foreach (var itmss in item.LineItem)
{
itemsal.Add(CreateWeeklyStockList(itmss));
}
}
// add this as method somewhere
WeeklyStockList CreateWeeklyStockList(LineItem lineItem)
{
string name = itmss.Item.Name.ToString(); // isn't Name already a string?
string code = itmss.Item.Code.ToString(); // isn't Code already a string?
string description = itmss.Item.Description.ToString(); // isn't Description already a string?
int quantity = Convert.ToInt32(itmss.Item.Quantity); // wouldn't (int) or "as int" be enough?
return new WeeklyStockList(
name,
code,
description,
quantity,
2, 2, 2, 2, 2, 2, 2, 2, 2
);
}
// also add this as a method
LineItem GetLineItem(IEnumerable<LineItem> lineItems)
{
// add a null-check
if(lineItems == null)
throw new ArgumentNullException("lineItems", "Argument cannot be null!");
// your original code
from sli in lineItems
group sli by sli.Item into ItemGroup
select new
{
Item = ItemGroup.Key,
Weeks = ItemGroup.Select(s => s.Week)
}
}
The code above is from the top of my head, of course, because I cannot know what type of classes you have and thus cannot test the code before posting. Nevertheless, if you edit it until it is correct (if it isn't so out of the box), then you already stand a large chance the actual error becomes a lot clearer. If not, you should at the very least see a different stacktrace this time (which we still eagerly await!).
The next step is to meticulously replace each part that can result in a null reference exception. By that I mean that you replace this:
select new
{
SaleID = sale.OrderID,
LineItem = GetLineItem(sale.LineItems)
};
with something like this:
select new
{
SaleID = 123,
LineItem = GetLineItem(new LineItem(/*ctor params for empty lineitem here*/))
};
This will create rubbish output, but will narrow the problem down even further to your potential offending line. Do the same as above for other places in the LINQ statements that can end up null
(just about everything).
This step you'll have to do yourself. But if LINQ fails and gives you such headaches and such unreadable or hard-to-debug code, consider what would happen with the next problem you encounter? And what if it fails on a live environment and you have to solve it under time pressure=
The moral: it's always good to learn new techniques, but sometimes it's even better to grab back to something that's clear and understandable. Nothing against LINQ, I love it, but in this particular case, let it rest, fix it with a simple loop and revisit it in half a year or so.
Actually, nothing to conclude. I went a bit further then I'd normally go with the long-extended answer. I just hope it helps you tackling the problem better and gives you some tools understand how you can narrow down hard-to-debug situations, even without advanced debugging techniques (which we haven't discussed).
If you can recompile all incompatible libs you use, do it with compiler option
-D_GLIBCXX_USE_CXX11_ABI=1
and then rebuild your project. If you can't do so, add to your project's makefile compiler option
-D_GLIBCXX_USE_CXX11_ABI=0
The define
#define _GLIBCXX_USE_CXX11_ABI 0/1
is also good but you probably need to add it to all your files while compiler option do it for all files at once.
int iInt = 10;
Integer iInteger = new Integer(iInt);
Try this
npm i react-router-dom@next
in your App.js
import { BrowserRouter as Router, Route } from 'react-router-dom'
const Home = () => <h1>Home</h1>
const App = () =>(
<Router>
<Route path="/" component={Home} />
</Router>
)
export default App;
Use geom_text
, with aes
label. You can play with hjust, vjust
to adjust text position.
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +geom_text(aes(label=Name),hjust=0, vjust=0)
ggplot(nba, aes(x= MIN, y= PTS, colour="green", label=Name))+
geom_point() +
geom_text(aes(label=ifelse(PTS>24,as.character(Name),'')),hjust=0,vjust=0)
You can use finish()
method or you can use:
android:noHistory="true"
And then there is no need to call finish()
anymore.
<activity android:name=".ClassName" android:noHistory="true" ... />
There are many efficient ways to test primality (and this isn't one of them), but the loop you wrote can be concisely rewritten in Python:
def is_prime(a):
return all(a % i for i in xrange(2, a))
That is, a is prime if all numbers between 2 and a (not inclusive) give non-zero remainder when divided into a.
Here is example:
$array = array("Jon","Smith");
foreach($array as $value) {
echo $value;
}
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
If you have missed to add unique to DB column, just add this validation in model to check if the field is unique:
class Person < ActiveRecord::Base
validates_uniqueness_of :user_name
end
refer here Above is for testing purpose only, please add index by changing DB column as suggested by @Nate
please refer this with index for more information
Here is how to do it programatically:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.your_awesome_color));
}
Using Compat library:
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(ContextCompat.getColor(this, R.color.primary));
}
Here is how to do it with xml in the values-v21/style.xml folder:
<item name="android:navigationBarColor">@color/your_color</item>
The complete example with an array. Replace "constructArrayType()" by "constructCollectionType()" or any other type you need.
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
public class Sorting {
private String property;
private String direction;
public Sorting() {
}
public Sorting(String property, String direction) {
this.property = property;
this.direction = direction;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
public static void main(String[] args) throws JsonParseException, IOException {
final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
ObjectMapper mapper = new ObjectMapper();
Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
System.out.println(sortings);
}
}
Another way is here
hash = {one: 1, two: 2}
hash.member?(:one)
#=> true
hash.member?(:five)
#=> false
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
It looks like changes after pandas 10.1/13.1
I upgraded from 10.1 to 13.1, before iloc is not available.
Now with 13.1, iloc[0]['label']
gets a single value array rather than a scalar.
Like this:
lastprice=stock.iloc[-1]['Close']
Output:
date
2014-02-26 118.2
name:Close, dtype: float64
You are using the incorrect overload of ActionLink. Try this
<%= Html.ActionLink("Create New Part", "CreateParts", "PartList", new { parentPartId = 0 }, null)%>
mongoexport --help
....
-f [ --fields ] arg comma separated list of field names e.g. -f name,age
--fieldFile arg file with fields names - 1 per line
You have to manually specify it and if you think about it, it makes perfect sense. MongoDB is schemaless; CSV, on the other hand, has a fixed layout for columns. Without knowing what fields are used in different documents it's impossible to output the CSV dump.
If you have a fixed schema perhaps you could retrieve one document, harvest the field names from it with a script and pass it to mongoexport.
Here is one possible solution to solve the problem without a library :
public static boolean delete(File file) {
File[] flist = null;
if(file == null){
return false;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
flist = file.listFiles();
if (flist != null && flist.length > 0) {
for (File f : flist) {
if (!delete(f)) {
return false;
}
}
}
return file.delete();
}
The difference between:
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
and
parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
is thus:
myscript.py
=> debug is 7 (from default) in the first case and "None" in the second
myscript.py --debug
=> debug is 1 in each case
myscript.py --debug 2
=> debug is 2 in each case
You may also want to check to see whether you're linking against the dynamic or static C runtime library. If your DLL files are linking against the static C runtime library, then the DLL files have separate heaps.
Hence, if you were to create an object in one DLL and try to free it in another DLL, you would get the same message you're seeing above. This problem is referenced in another Stack Overflow question, Freeing memory allocated in a different DLL.
Here is a "minimal" solution.
class SortedArrayList<T> extends ArrayList<T> {
@SuppressWarnings("unchecked")
public void insertSorted(T value) {
add(value);
Comparable<T> cmp = (Comparable<T>) value;
for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
Collections.swap(this, i, i-1);
}
}
The insert runs in linear time, but that would be what you would get using an ArrayList anyway (all elements to the right of the inserted element would have to be shifted one way or another).
Inserting something non-comparable results in a ClassCastException. (This is the approach taken by PriorityQueue
as well: A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).)
List.add
Note that overriding List.add
(or List.addAll
for that matter) to insert elements in a sorted fashion would be a direct violation of the interface specification. What you could do, is to override this method to throw an UnsupportedOperationException
.
From the docs of List.add
:
boolean add(E e)
Appends the specified element to the end of this list (optional operation).
Same reasoning applies for both versions of add
, both versions of addAll
and set
. (All of which are optional operations according to the list interface.)
SortedArrayList<String> test = new SortedArrayList<String>();
test.insertSorted("ddd"); System.out.println(test);
test.insertSorted("aaa"); System.out.println(test);
test.insertSorted("ccc"); System.out.println(test);
test.insertSorted("bbb"); System.out.println(test);
test.insertSorted("eee"); System.out.println(test);
....prints:
[ddd]
[aaa, ddd]
[aaa, ccc, ddd]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]
I can't tell you whether or not this is correct, but I am using a Bitnami image over Google Compute App Engine. I has having problems with plugins and migration, and after further messing things up by chmod'ing permissions, I found these three lines which solved all my problems. Not sure if it's the proper way but worked for me.
sudo chown -R bitnami:daemon /opt/bitnami/apps/wordpress/htdocs/
sudo find /opt/bitnami/apps/wordpress/htdocs/ -type f -exec chmod 664 {} \;
sudo find /opt/bitnami/apps/wordpress/htdocs/ -type d -exec chmod 775 {} \;
Assuming you are on 10g, you can also use the MERGE statement. This allows you to insert the row if it doesn't exist and ignore the row if it does exist. People tend to think of MERGE when they want to do an "upsert" (INSERT if the row doesn't exist and UPDATE if the row does exist) but the UPDATE part is optional now so it can also be used here.
SQL> create table foo (
2 name varchar2(10) primary key,
3 age number
4 );
Table created.
SQL> ed
Wrote file afiedt.buf
1 merge into foo a
2 using (select 'johnny' name, null age from dual) b
3 on (a.name = b.name)
4 when not matched then
5 insert( name, age)
6* values( b.name, b.age)
SQL> /
1 row merged.
SQL> /
0 rows merged.
SQL> select * from foo;
NAME AGE
---------- ----------
johnny
If you are using chrome: try open chrome with the args to disable web security like you see here:
One quick note. Generators are cancellable, async/await — not. So for an example from the question, it does not really make sense of what to pick. But for more complicated flows sometimes there is no better solution than using generators.
So, another idea could be is to use generators with redux-thunk, but for me, it seems like trying to invent a bicycle with square wheels.
And of course, generators are easier to test.
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
Go into your AndroidManifest.xml file
Enjoy using a gui rather then messing with an image editor! Hope this helps!
From cran, you can install directly from a github repository address. So if you want the package at https://github.com/twitter/AnomalyDetection
:
library(devtools)
install_github("twitter/AnomalyDetection")
does the trick.
As @cs95 mentioned in a comment, to drop only one level, use:
df.reset_index(level=[...])
This avoids having to redefine your desired index after reset.
The question is really about scope, as the other guy put it.
In short, consider this "module":
Public Var1 As variant 'Var1 can be used in all
'modules, class modules and userforms of
'thisworkbook and will preserve any values
'assigned to it until either the workbook
'is closed or the project is reset.
Dim Var2 As Variant 'Var2 and Var3 can be used anywhere on the
Private Var3 As Variant ''current module and will preserve any values
''they're assigned until either the workbook
''is closed or the project is reset.
Sub MySub() 'Var4 can only be used within the procedure MySub
Dim Var4 as Variant ''and will only store values until the procedure
End Sub ''ends.
Sub MyOtherSub() 'You can even declare another Var4 within a
Dim Var4 as Variant ''different procedure without generating an
End Sub ''error (only possible confusion).
You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.
Two other quick things:
According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.
SELECT IDENT_CURRENT('Table')
You can use one of these examples:
SELECT * FROM Table
WHERE ID = (
SELECT IDENT_CURRENT('Table'))
SELECT * FROM Table
WHERE ID = (
SELECT MAX(ID) FROM Table)
SELECT TOP 1 * FROM Table
ORDER BY ID DESC
But the first one will be more efficient because no index scan is needed (if you have index on Id column).
The second one solution is equivalent to the third (both of them need to scan table to get max id).
MATLAB, as mentioned by others, is great at matrix manipulation, and was originally built as an extension of the well-known BLAS and LAPACK libraries used for linear algebra. It interfaces well with other languages like Java, and is well favored by engineering and scientific companies for its well developed and documented libraries. From what I know of Python and NumPy, while they share many of the fundamental capabilities of MATLAB, they don't have the full breadth and depth of capabilities with their libraries.
Personally, I use MATLAB because that's what I learned in my internship, that's what I used in grad school, and that's what I used in my first job. I don't have anything against Python (or any other language). It's just what I'm used too.
Also, there is another free version in addition to scilab mentioned by @Jim C from gnu called Octave.
Wrong method was used for errors, here is the working code:
BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.
Sub CleanTheTable()
Application.ScreenUpdating = False
Sheets("Data").Select
ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
'Remove the filters if one exists.
If ActiveSheet.FilterMode Then
Selection.AutoFilter
End If
'Clear all lines but the first one in the table leaving formulas for the next go round.
With Worksheets("Data").ListObjects("TestTable")
.Range.AutoFilter
On Error Resume Next
.DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
ActiveWindow.SmallScroll Down:=-10000
End With
Application.ScreenUpdating = True
End Sub
I fixed it by moving the start()
function inside the dismiss
completion block:
self.tabBarController.dismiss(animated: false) {
self.start()
}
Start contains two calls to self.present()
one for a UINavigationController and another one for a UIImagePickerController
.
That fixed it for me.
Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.
Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:
{
"/api": {
"target": "http://localhost:49389",
"secure": true,
"pathRewrite": {
"^/api": "/api"
},
"changeOrigin": true
}
}
Put the file in the same directory the package.json then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from the app component is as follows:
return this.http.get('/api/customers').map((res: Response) => res.json());
Lastly to run use npm start or ng serve --proxy-config proxy.conf.json
You can compile Kotlin to bytecode, then use a Java disassembler.
The decompiling may be done inside IntelliJ Idea, or using FernFlower https://github.com/fesh0r/fernflower (thanks @Jire)
There was no automated tool as I checked a couple months ago (and no plans for one AFAIK)
For the people looking for regular polygons:
function regPolyPath(r,p,ctx){ //Radius, #points, context
//Azurethi was here!
ctx.moveTo(r,0);
for(i=0; i<p+1; i++){
ctx.rotate(2*Math.PI/p);
ctx.lineTo(r,0);
}
ctx.rotate(-2*Math.PI/p);
}
Use:
//Get canvas Context
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.translate(60,60); //Moves the origin to what is currently 60,60
//ctx.rotate(Rotation); //Use this if you want the whole polygon rotated
regPolyPath(40,6,ctx); //Hexagon with radius 40
//ctx.rotate(-Rotation); //remember to 'un-rotate' (or save and restore)
ctx.stroke();
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Go to the actual FILE menu and create a new general project.
If the project type isn't recognized, preventing one of these import methods from working, then try this. Once you add the generic project, you can then add support for whatever language you require.
Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.
(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )
It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:
define('SMTP_SERVER', 'smtp.ebola.cz');
into this:
define('SMTP_SERVER', 'ssl://smtp.ebola.cz');
I can't seem to wrap my head around why this does not work.
Because main
returns a promise; all async
functions do.
At the top level, you must either:
Use a top-level async
function that never rejects (unless you want "unhandled rejection" errors), or
Use then
and catch
, or
(Coming soon!) Use top-level await
, a proposal that has reached Stage 3 in the process that allows top-level use of await
in a module.
async
function that never rejects(async () => {
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
})();
Notice the catch
; you must handle promise rejections / async exceptions, since nothing else is going to; you have no caller to pass them on to. If you prefer, you could do that on the result of calling it via the catch
function (rather than try
/catch
syntax):
(async () => {
var text = await main();
console.log(text);
})().catch(e => {
// Deal with the fact the chain failed
});
...which is a bit more concise (I like it for that reason).
Or, of course, don't handle errors and just allow the "unhandled rejection" error.
then
and catch
main()
.then(text => {
console.log(text);
})
.catch(err => {
// Deal with the fact the chain failed
});
The catch
handler will be called if errors occur in the chain or in your then
handler. (Be sure your catch
handler doesn't throw errors, as nothing is registered to handle them.)
Or both arguments to then
:
main().then(
text => {
console.log(text);
},
err => {
// Deal with the fact the chain failed
}
);
Again notice we're registering a rejection handler. But in this form, be sure that neither of your then
callbacks doesn't throw any errors, nothing is registered to handle them.
await
in a moduleYou can't use await
at the top level of a non-module script, but the top-level await
proposal (Stage 3) allows you to use it at the top level of a module. It's similar to using a top-level async
function wrapper (#1 above) in that you don't want your top-level code to reject (throw an error) because that will result in an unhandled rejection error. So unless you want to have that unhandled rejection when things go wrong, as with #1, you'd want to wrap your code in an error handler:
// In a module, once the top-level `await` proposal lands
try {
var text = await main();
console.log(text);
} catch (e) {
// Deal with the fact the chain failed
}
Note that if you do this, any module that imports from your module will wait until the promise you're await
ing settles; when a module using top-level await
is evaluated, it basically returns a promise to the module loader (like an async
function does), which waits until that promise is settled before evaluating the bodies of any modules that depend on it.
On new El Capitan installation where SIP(rootless prevents access to usr/lib/) is on by default and you cannot create the symlink unless you are in recovery mode. As @yannisxu said you can disable SIP and do your symlink to /usr/lib/local and this will work.
you can use the following command on MAC OSX El Capitan instead of turning off SIP:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
There used to be an option where you can login as root and this can disable SIP but in the final release that is now obsolete, you can read more about it here: https://forums.developer.apple.com/thread/4686
Question:
There is a nvram boot-args command available in Developer Beta 1 which can disable SIP when run with root privileges:
nvram boot-args="rootless=0"
Will this option of disabling SIP also be available in the El Capitan release version? Or is this strictly for the Developer Builds?
Answer:
This nvram boot-args command will be going away. It will not be available in the El Capitan release version and may disappear before the end of the Developer Betas. Keep an eye on the release notes for future Developer Betas.
The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.
One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder
conda create -n newenvt anaconda python=3.5
activate newenvt
and then install tensorflow into newenvt
I found this primer helpful
UPDATE: Somebody just won't take no as the answer, and I like it, very much, especially to this particular question.
GOOD NEWS, There is a way now --
The solution is Rocker: https://github.com/grammarly/rocker
John Yani said, "IMO, it solves all the weak points of Dockerfile, making it suitable for development."
https://github.com/grammarly/rocker
By introducing new commands, Rocker aims to solve the following use cases, which are painful with plain Docker:
- Mount reusable volumes on build stage, so dependency management tools may use cache between builds.
- Share ssh keys with build (for pulling private repos, etc.), while not leaving them in the resulting image.
- Build and run application in different images, be able to easily pass an artifact from one image to another, ideally have this logic in a single Dockerfile.
- Tag/Push images right from Dockerfiles.
- Pass variables from shell build command so they can be substituted to a Dockerfile.
And more. These are the most critical issues that were blocking our adoption of Docker at Grammarly.
As of early 2018, the container ecosystem is much more mature than it was three years ago when this project was initiated. Now, some of the critical and outstanding features of rocker can be easily covered by docker build or other well-supported tools, though some features do remain unique to rocker. See https://github.com/grammarly/rocker/issues/199 for more details.
I've got two points to add. One, Hudson/Jenkins is all about the plugins. Plugin developers have moved to Jenkins and so should we, the users. Two, I am not personally a big fan of Oracle's products. In fact, I avoid them like the plague. For the money spent on licensing and hardware for an Oracle solution you can hire twice the engineering staff and still have some left over to buy beer every Friday :)
I think it is a problem(aka. bug) with the API you are using. JSONArray
implements Collection
(the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject
has an overloaded put()
method which takes a Collection and wraps it in a JSONArray
(thus causing the problem). I think you need to force the other JSONObject.put()
method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection)
method is broken.
Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.
ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.
The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).
A better option
Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE
). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses
(and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.
On the anaconda prompt, do a
conda -V
or conda --version
to get the conda version.python -V
or python --version
to get the python version.conda list anaconda$
to get the Anaconda version.conda list
to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).conda info
to get all the current environment details.conda info --envs
To see a list of all your environmentsUsing T-SQL:
My job is executing stored procedure. You can easy change @command
to run your sql.
EXEC msdb.dbo.sp_add_job
@job_name = N'MakeDailyJob',
@enabled = 1,
@description = N'Procedure execution every day' ;
EXEC msdb.dbo.sp_add_jobstep
@job_name = N'MakeDailyJob',
@step_name = N'Run Procedure',
@subsystem = N'TSQL',
@command = 'exec BackupFromConfig';
EXEC msdb.dbo.sp_add_schedule
@schedule_name = N'Everyday schedule',
@freq_type = 4, -- daily start
@freq_interval = 1,
@active_start_time = '230000' ; -- start time 23:00:00
EXEC msdb.dbo.sp_attach_schedule
@job_name = N'MakeDailyJob',
@schedule_name = N'Everyday schedule' ;
EXEC msdb.dbo.sp_add_jobserver
@job_name = N'MakeDailyJob',
@server_name = @@servername ;
You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361
using System;
using System.Collections.Generic; (???????? ?????????? ?? ?? ?????
using System.Linq; ?????? PlayerScript.health =
using System.Text; 999999; ??? ?? ???? ??????)
using System.Threading.Tasks;
using UnityEngine;
namespace OneHack
{
public class One
{
public Rect RT_MainMenu = new Rect(0f, 100f, 120f, 100f); //Rect ??? ????????????????? ???? ?? x,y ? ??????, ??????.
public int ID_RTMainMenu = 1;
private bool MainMenu = true;
private void Menu_MainMenu(int id) //??????? ????
{
if (GUILayout.Button("???????? ????? ??????", new GUILayoutOption[0]))
{
if (GUILayout.Button("??????????", new GUILayoutOption[0]))
{
PlayerScript.health = 999999;//??? ??????? ?? ?????? ? ?????? ??????????????? ???????? 999999 //????? ???, ??????? ????? ??????????? ??? ??????? ?? ??? ??????
}
}
}
private void OnGUI()
{
if (this.MainMenu)
{
this.RT_MainMenu = GUILayout.Window(this.ID_RTMainMenu, this.RT_MainMenu, new GUI.WindowFunction(this.Menu_MainMenu), "MainMenu", new GUILayoutOption[0]);
}
}
private void Update() //????????? ??????????? ?????, ??? ??? ????? ????? ????????? ????? ??????????? ??????????
{
if (Input.GetKeyDown(KeyCode.Insert)) //?????? ?? ??????? ????? ??????????? ? ??????????? ????, ????? ????????? ??????
{
this.MainMenu = !this.MainMenu;
}
}
}
}
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):
function getXY(evt) {
var element = document.getElementById('elementId'); //replace elementId with your element's Id.
var rect = element.getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop?
document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?
document.documentElement.scrollLeft:document.body.scrollLeft;
var elementLeft = rect.left+scrollLeft;
var elementTop = rect.top+scrollTop;
if (document.all){ //detects using IE
x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
y = event.clientY+scrollTop-elementTop;
}
else{
x = evt.pageX-elementLeft;
y = evt.pageY-elementTop;
}
I had a similar problem but with a twist - the solutions listed above worked when the resultset was from one query but in my situation, I had multiple individual select queries for which I needed results to be exported to Excel. Below is just an example to illustrate although I could do a name in
clause...
select a,b from Table_A where name = 'x'
select a,b from Table_A where name = 'y'
select a,b from Table_A where name = 'z'
The wizard was letting me export the result from one query to excel but not all results from different queries in this case.
When I researched, I found that we could disable the results to grid and enable results to Text. So, press Ctrl + T, then execute all the statements. This should show the results as a text file in the output window. You can manipulate the text into a tab delimited format for you to import into Excel.
You could also press Ctrl + Shift + F to export the results to a file - it exports as a .rpt file that can be opened using a text editor and manipulated for excel import.
Hope this helps any others having a similar issue.
Do this:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
create check.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
If someone looking for calling a script with arguments
import subprocess
val = subprocess.check_call("./script.sh '%s'" % arg, shell=True)
Remember to convert the args to string before passing, using str(arg).
This can be used to pass as many arguments as desired:
subprocess.check_call("./script.ksh %s %s %s" % (arg1, str(arg2), arg3), shell=True)
jakub.g's answer is correct, however an example using grunt seems a bit complex.
So my simpler answer:
- Sending a command line argument to an npm script
Syntax for sending command line arguments to an npm script:
npm run [command] [-- <args>]
Imagine we have an npm start task in our package.json to kick off webpack dev server:
"scripts": {
"start": "webpack-dev-server --port 5000"
},
We run this from the command line with npm start
Now if we want to pass in a port to the npm script:
"scripts": {
"start": "webpack-dev-server --port process.env.port || 8080"
},
running this and passing the port e.g. 5000 via command line would be as follows:
npm start --port:5000
- Using package.json config:
As mentioned by jakub.g, you can alternatively set params in the config of your package.json
"config": {
"myPort": "5000"
}
"scripts": {
"start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},
npm start
will use the port specified in your config, or alternatively you can override it
npm config set myPackage:myPort 3000
- Setting a param in your npm script
An example of reading a variable set in your npm script. In this example NODE_ENV
"scripts": {
"start:prod": "NODE_ENV=prod node server.js",
"start:dev": "NODE_ENV=dev node server.js"
},
read NODE_ENV in server.js either prod or dev
var env = process.env.NODE_ENV || 'prod'
if(env === 'dev'){
var app = require("./serverDev.js");
} else {
var app = require("./serverProd.js");
}
import pandas as pd
data = pd.read_excel (r'**YourPath**.xlsx')
print (data)
If you're looking for a Kafka error, this might because the upgrade of Kafka's version from 1.x to 2.x.
javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... java.security.cert.CertificateException: No name matching *** found
or
[Producer clientId=producer-1] Connection to node -2 failed authentication due to: SSL handshake failed
The default value for ssl.endpoint.identification.algorithm was changed to https, which performs hostname verification (man-in-the-middle attacks are possible otherwise). Set ssl.endpoint.identification.algorithm to an empty string to restore the previous behaviour. Apache Kafka Notable changes in 2.0.0
Solution: SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""
From Windows 10 version 1607, the limitation has been removed by setting a registry key
Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom property, which you can then access using this
in the success callback:
//preloader for images on gallery pages
window.onload = function() {
var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];
setTimeout(function() {
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
indexValue: i,
success: function(data) {
image_link(data , this.indexValue);
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
console.log(i);
new Image().src = urls[i] + $(this).attr("href");
});
}
}
});
};
}, 1000);
};
Edit: Adding in an updated JSFiddle example, as they seem to have changed how their ECHO endpoints work: https://jsfiddle.net/djujx97n/26/.
To understand how this works see the "context" field on the ajaxSettings object: http://api.jquery.com/jquery.ajax/, specifically this note:
"The
this
reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves."
You're trying to import a huge dataset via a web interface.
By default PHP scripts run in the context of a web server have a maximum execution time limit because you don't want a single errant PHP script tying up the entire server and causing a denial of service.
For that reason your import is failing. PHPMyAdmin is a web application and is hitting the limit imposed by PHP.
You could try raising the limit but that limit exists for a good reason so that's not advisable. Running a script that is going to take a very long time to execute in a web server is a very bad idea.
PHPMyAdmin isn't really intended for heavy duty jobs like this, it's meant for day to day housekeeping tasks and troubleshooting.
Your best option is to use the proper tools for the job, such as the mysql commandline tools. Assuming your file is an SQL dump then you can try running the following from the commandline:
mysql -u(your user name here) -p(your password here) -h(your sql server name here) (db name here) < /path/to/your/sql/dump.sql
Or if you aren't comfortable with commandline tools then something like SQLYog (for Windows), Sequel Pro (for Mac), etc may be more suitable for running an import job
I found this for online php validation:-
http://www.icosaedro.it/phplint/phplint-on-line.html
Hope this helps.
You can also use the constant service as such. Defining the function outside of the constant call allows it to be recursive as well.
function doSomething( a, b ) {
return a + b;
};
angular.module('moduleName',[])
// Define
.constant('$doSomething', doSomething)
// Usage
.controller( 'SomeController', function( $doSomething ) {
$scope.added = $doSomething( 100, 200 );
})
;
First you have to install a module call Serial. To do that go to the folder call Scripts which is located in python installed folder. If you are using Python 3 version it's normally located in location below,
C:\Python34\Scripts
Once you open that folder right click on that folder with shift key. Then click on 'open command window here'. After that cmd
will pop up. Write the below code in that cmd
window,
pip install PySerial
and press enter.after that PySerial module will be installed. Remember to install the module u must have an INTERNET connection.
after successfully installed the module open python IDLE and write down the bellow code and run it.
import serial
# "COM11" is the port that your Arduino board is connected.set it to port that your are using
ser = serial.Serial("COM11", 9600)
while True:
cc=str(ser.readline())
print(cc[2:][:-5])
pip list
List installed packages: show ALL installed packages that even pip installed implictly
pip freeze
List installed packages: - list of packages that are installed using pip command
pip freeze has --all
flag to show all the packages.
Other difference is the output it renders, that you can check by running the commands.
ffmpeg has been substituted by avconv: just substitute avconb to Louis Marascio's answer.
avconv -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start.*/\1/g'
Note: the aditional .* after start to get the time alone !!
Well, the C way might be something like ...
#include <stdlib.h>
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
printf("%X", n);
exit(0);
}
Here are two very short texts to compare:
Julie loves me more than Linda loves me
Jane likes me more than Julie loves me
We want to know how similar these texts are, purely in terms of word counts (and ignoring word order). We begin by making a list of the words from both texts:
me Julie loves Linda than more likes Jane
Now we count the number of times each of these words appears in each text:
me 2 2
Jane 0 1
Julie 1 1
Linda 1 0
likes 0 1
loves 2 1
more 1 1
than 1 1
We are not interested in the words themselves though. We are interested only in those two vertical vectors of counts. For instance, there are two instances of 'me' in each text. We are going to decide how close these two texts are to each other by calculating one function of those two vectors, namely the cosine of the angle between them.
The two vectors are, again:
a: [2, 0, 1, 1, 0, 2, 1, 1]
b: [2, 1, 1, 0, 1, 1, 1, 1]
The cosine of the angle between them is about 0.822.
These vectors are 8-dimensional. A virtue of using cosine similarity is clearly that it converts a question that is beyond human ability to visualise to one that can be. In this case you can think of this as the angle of about 35 degrees which is some 'distance' from zero or perfect agreement.
Yes, use gzip for this. The best way is to read data as input and redirect the compressed to output file i.e.
cat test.csv | gzip > test.csv.gz
cat test.csv
will send the data as stdout and using pipe-sign gzip will read that data as stdin. Make sure to redirect the gzip output to some file as compressed data will not be written to the terminal.
You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension
In your case, j3evn.jpg.
How not to do it:
When building an image, you could also tag it this way.
docker build -t ubuntu:14.04 .
Then you build it again with another tag:
docker build -t ubuntu:latest .
If your Dockerfile makes good use of the cache, the same image should come out, and it effectively does the same as retagging the same image. If you do docker images
then you will see that they have the same ID.
There's probably a case where this goes wrong though... But like @david-braun said, you can't create tags with Dockerfiles themselves, just with the docker command.
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
array_push == $res_arr_values[] = $row;
example
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
?>
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
Assuming the question is about cleaning the workspace of the current job, you can run:
test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*
found one interesting cheat sheet here.. http://introcs.cs.princeton.edu/java/11cheatsheet/
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
You can tweak the string to split by - if you use "code : "
, the second member of the returned array ([1]
) will contain "-1"
, using your example.
In LinearLayout
, use: android:layout_gravity="center"
.
In RelativeLayout
, use: android:layout_centerInParent="true"
.
I am using Windows 8 and the above solutions did not work out for me. I downgraded Postgres from 9.4 to 9.3. Man,it worked :)
treeViewMain.SelectedNode = treeViewMain.Nodes.Find(searchNode, true)[0];
where searchNode is the name of the node. I'm personally using a combo "Node + Panel" where Node name is Node + and the same tag is also set on panel of choice. With this command + scan of panels by tag i'm usually able to work a treeview+panel full menu set.
This will cover all the possibility of a prime number . (order of the last 3 if statements is important)
function isPrime(num){
if (num==0 || num==1) return false;
if (num==2 || num==3 ) return true;
if (num % Math.sqrt(num)==0 ) return false;
for (let i=2;i< Math.floor(Math.sqrt(num));i++) if ( num % i==0 ) return false;
if ((num * num - 1) % 24 == 0) return true;
}
I came by the same error on an old 2010 Exchange Server. A service(Exchange mailbox replication service) was giving out the above error and the migration process could not be continued. Searching through the internet, i came by this link which stated the below:
The Exchange GRE fails to open when installed for the first time or if any changes are made to the IIS server. It fails with snap-in error and when you try to open the snap-in page, the following content is displayed:
This collection already contains an address with scheme http. There can be at most one address per scheme in this collection. If your service is being hosted in IIS you can fix the problem by setting 'system.serviceModel/serviceHostingEnvironment/multipleSiteBindingsEnabled' to true or specifying 'system.serviceModel/serviceHostingEnvironment/baseAddressPrefixFilters'."
Cause: This error occurs because http port number 443 is already in use by another application and the IIS server is not configured to handle multiple binding to the same port.
Solution: Configure IIS server to handle multiple port bindings. Contact the vendor (Microsoft) to configure it.
Since these services were offered from an IIS Web Server, checking the Bindings on the Root Site fixed the problem. Someone had messed up the Site Bindings, defining rules that were overlapping themselves and messed up the services.
Fixing the correct Bindings resolved the problem, in my case, and i did not have to configure the Web.Config.
try this method, working fine for me
position: absolute;
left: 50%;
transform: translateX(-50%);
If you have Notepad++ and you get this .sh Error Message: "command not found" or this autoconf Error Message "line 615: ../../autoconf/bin/autom4te: No such file or directory".
On your Notepad++, Go to Edit -> EOL Conversion then check Macinthos(CR). This will edit your files. I also encourage to check all files with this command, because soon such an error will occur.
This one works for me
<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>
To programmatically maximize the windowstate you can use:
this.WindowState = FormWindowState.Maximized;
this.MaximizeBox = false;
AnimationSets don't appear to work as expected at all. In the end I gave up and used the Handler class's postDelayed() to sequence animations.
By using this you can get the text, value and data attribute.
<select name="your_name" id="your_id" onchange="getSelectedDataAttribute(this)">
<option value="1" data-id="123">One</option>
<option value="2" data-id="234">Two</option>
</select>
function getSelectedDataAttribute(event) {
var selected_text = event.options[event.selectedIndex].innerHTML;
var selected_value = event.value;
var data-id = event.options[event.selectedIndex].dataset.id);
}
Here are some vendors you might me looking for
::-webkit-input-placeholder {color: tomato}
::-moz-placeholder {color: tomato;} /* Firefox 19+ */
:-moz-placeholder {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder {color: tomato;}
You can also style different states, such as focus
:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder {color: transparent}
:focus:-moz-placeholder {color: transparent}
:focus:-ms-input-placeholder {color: transparent}
You can also do certain transitions on it, like
::-VENDOR-input-placeholder {text-indent: 0px; transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder {text-indent: 500px; transition: text-indent 0.3s ease;}
I thought my simple "all possible combination generator" might help someone, i think its a really good example for building something bigger and better
you can change N (characters) to any you like by just removing/adding from string array (you can change it to int as well). Current amount of characters is 36
you can also change K (size of the generated combinations) by just adding more loops, for each element, there must be one extra loop. Current size is 4
#include<iostream>
using namespace std;
int main() {
string num[] = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z" };
for (int i1 = 0; i1 < sizeof(num)/sizeof(string); i1++) {
for (int i2 = 0; i2 < sizeof(num)/sizeof(string); i2++) {
for (int i3 = 0; i3 < sizeof(num)/sizeof(string); i3++) {
for (int i4 = 0; i4 < sizeof(num)/sizeof(string); i4++) {
cout << num[i1] << num[i2] << num[i3] << num[i4] << endl;
}
}
}
}}
Result
0: A A A
1: B A A
2: C A A
3: A B A
4: B B A
5: C B A
6: A C A
7: B C A
8: C C A
9: A A B
...
just keep in mind that the amount of combinations can be ridicules.
--UPDATE--
a better way to generate all possible combinations would be with this code, which can be easily adjusted and configured in the "variables" section of the code.
#include<iostream>
#include<math.h>
int main() {
//VARIABLES
char chars[] = { 'A', 'B', 'C' };
int password[4]{0};
//SIZES OF VERIABLES
int chars_length = sizeof(chars) / sizeof(char);
int password_length = sizeof(password) / sizeof(int);
//CYCKLE TROUGH ALL OF THE COMBINATIONS
for (int i = 0; i < pow(chars_length, password_length); i++){
//CYCKLE TROUGH ALL OF THE VERIABLES IN ARRAY
for (int i2 = 0; i2 < password_length; i2++) {
//IF VERIABLE IN "PASSWORD" ARRAY IS THE LAST VERIABLE IN CHAR "CHARS" ARRRAY
if (password[i2] == chars_length) {
//THEN INCREMENT THE NEXT VERIABLE IN "PASSWORD" ARRAY
password[i2 + 1]++;
//AND RESET THE VERIABLE BACK TO ZERO
password[i2] = 0;
}}
//PRINT OUT FIRST COMBINATION
std::cout << i << ": ";
for (int i2 = 0; i2 < password_length; i2++) {
std::cout << chars[password[i2]] << " ";
}
std::cout << "\n";
//INCREMENT THE FIRST VERIABLE IN ARRAY
password[0]++;
}}
public static boolean isParsable(String input) {
try {
Integer.parseInt(input);
return true;
} catch (final NumberFormatException e) {
return false;
}
}
I was able to solve this problem by cleaning my build.
Top menu -> Product -> Clean Or keyboard shortcut: Shift+Cmd+K
Using create will cause one query per new item. If you want to reduce the number of INSERT queries, you'll need to use something else.
I've had some success using the Bulk Insert snippet, even though the snippet is quite old. Perhaps there are some changes required to get it working again.
I realize that it's been a while since there has been any new activity on this question. But, as other posters have commented - get_result()
is now only available in PHP by installing the MySQL native driver (mysqlnd), and in some cases, it may not be possible or desirable to install mysqlnd. So, I thought it would be helpful to post this answer with info on how get the functionality that get_result()
offers - without using get_result()
.
get_result()
is/was often combined with fetch_array()
to loop through a result set and store the values from each row of the result set in a numerically-indexed or associative array. For example, the code below uses get_result() with fetch_array() to loop through a result set, storing the values from each row in the numerically-indexed $data[] array:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$result = $stmt->get_result();
while($data = $result->fetch_array(MYSQLI_NUM)) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
However, if get_result()
is not available (because mysqlnd is not installed), then this leads to the problem of how to store the values from each row of a result set in an array, without using get_result()
. Or, how to migrate legacy code that uses get_result()
to run without it (e.g. using bind_result()
instead) - while impacting the rest of the code as little as possible.
It turns out that storing the values from each row in a numerically-indexed array is not so straight-forward using bind_result()
. bind_result()
expects a list of scalar variables (not an array). So, it takes some doing to make it store the values from each row of the result set in an array.
Of course, the code could easily be modified as follows:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$stmt->bind_result($data[0], $data[1]);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
But, this requires us to explicitly list $data[0], $data[1], etc. individually in the call to bind_result()
, which is not ideal. We want a solution that doesn't require us to have to explicitly list $data[0], $data[1], ... $data[N-1] (where N is the number of fields in the select statement) in the call to bind_results()
. If we're migrating a legacy application that has a large number of queries, and each query may contain a different number of fields in the select
clause, the migration will be very labor intensive and prone to error if we use a solution like the one above.
Ideally, we want a snippet of 'drop-in replacement' code - to replace just the line containing the get_result()
function and the while() loop on the next line. The replacement code should have the same function as the code that it's replacing, without affecting any of the lines before, or any of the lines after - including the lines inside the while() loop. Ideally we want the replacement code to be as compact as possible, and we don't want to have to taylor the replacement code based on the number of fields in the select
clause of the query.
Searching on the internet, I found a number of solutions that use bind_param()
with call_user_func_array()
(for example, Dynamically bind mysqli_stmt parameters and then bind result (PHP)), but most solutions that I found eventually lead to the results being stored in an associative array, not a numerically-indexed array, and many of these solutions were not as compact as I would like and/or were not suited as 'drop-in replacements'. However, from the examples that I found, I was able to cobble together this solution, which fits the bill:
$c=1000;
$sql="select account_id, username from accounts where account_id<?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('i', $c);
$stmt->execute();
$data=array();
for ($i=0;$i<$mysqli->field_count;$i++) {
$var = $i;
$$var = null;
$data[$var] = &$$var;
}
call_user_func_array(array($stmt,'bind_result'), $data);
while ($stmt->fetch()) {
print $data[0] . ', ' . $data[1] . "<BR>\n";
}
Of course, the for() loop can be collapsed into one line to make it more compact.
I hope this helps anyone who is looking for a solution using bind_result()
to store the values from each row in a numerically-indexed array and/or looking for a way to migrate legacy code using get_result()
. Comments welcome.
The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html
A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.
"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).
Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.
The table itself is always structured the same way it is in HTML.
In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):
<table ..>
<col .. />
<col .. />
<tr ..>
<td ..></td>
<td ..></td>
</tr>
<tr ..>
<td ..></td>
<td ..></td>
</tr>
</table>
Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):
.mytable {_x000D_
display: table;_x000D_
}_x000D_
.myrow {_x000D_
display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
display: table-column;_x000D_
background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 1</div>_x000D_
<div class="mycell">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow">_x000D_
<div class="mycell">contents of first cell in row 2</div>_x000D_
<div class="mycell">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
<div class="column1"></div>_x000D_
<div class="column2"></div>_x000D_
<div class="myrow row1">_x000D_
<div class="mycell cell1">contents of first cell in row 1</div>_x000D_
<div class="mycell cell2">contents of second cell in row 1</div>_x000D_
</div>_x000D_
<div class="myrow row2">_x000D_
<div class="mycell cell1">contents of first cell in row 2</div>_x000D_
<div class="mycell cell2">contents of second cell in row 2</div>_x000D_
</div>_x000D_
</div>
_x000D_
In today's flexible designs, which use <div>
for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr>
in HTML became class myrow
, and <td>
became class mycell
. This convention is what makes the above CSS selectors useful.
PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *
, such as .row1 *
or even .row1 > *
. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 *
first does *
, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1
. This might be slow in a complex document on a slow device. .row1 > *
is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1
. (.row1 > .cell1
is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >
.)
The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *
.
Blob datatypes stores binary objects like images while text datatypes stores text objects like articles of webpages
I can elaborate on the details of DLLs in Windows to help clarify those mysteries to my friends here in *NIX-land...
A DLL is like a Shared Object file. Both are images, ready to load into memory by the program loader of the respective OS. The images are accompanied by various bits of metadata to help linkers and loaders make the necessary associations and use the library of code.
Windows DLLs have an export table. The exports can be by name, or by table position (numeric). The latter method is considered "old school" and is much more fragile -- rebuilding the DLL and changing the position of a function in the table will end in disaster, whereas there is no real issue if linking of entry points is by name. So, forget that as an issue, but just be aware it's there if you work with "dinosaur" code such as 3rd-party vendor libs.
Windows DLLs are built by compiling and linking, just as you would for an EXE (executable application), but the DLL is meant to not stand alone, just like an SO is meant to be used by an application, either via dynamic loading, or by link-time binding (the reference to the SO is embedded in the application binary's metadata, and the OS program loader will auto-load the referenced SO's). DLLs can reference other DLLs, just as SOs can reference other SOs.
In Windows, DLLs will make available only specific entry points. These are called "exports". The developer can either use a special compiler keyword to make a symbol an externally-visible (to other linkers and the dynamic loader), or the exports can be listed in a module-definition file which is used at link time when the DLL itself is being created. The modern practice is to decorate the function definition with the keyword to export the symbol name. It is also possible to create header files with keywords which will declare that symbol as one to be imported from a DLL outside the current compilation unit. Look up the keywords __declspec(dllexport) and __declspec(dllimport) for more information.
One of the interesting features of DLLs is that they can declare a standard "upon load/unload" handler function. Whenever the DLL is loaded or unloaded, the DLL can perform some initialization or cleanup, as the case may be. This maps nicely into having a DLL as an object-oriented resource manager, such as a device driver or shared object interface.
When a developer wants to use an already-built DLL, she must either reference an "export library" (*.LIB) created by the DLL developer when she created the DLL, or she must explicitly load the DLL at run time and request the entry point address by name via the LoadLibrary() and GetProcAddress() mechanisms. Most of the time, linking against a LIB file (which simply contains the linker metadata for the DLL's exported entry points) is the way DLLs get used. Dynamic loading is reserved typically for implementing "polymorphism" or "runtime configurability" in program behaviors (accessing add-ons or later-defined functionality, aka "plugins").
The Windows way of doing things can cause some confusion at times; the system uses the .LIB extension to refer to both normal static libraries (archives, like POSIX *.a files) and to the "export stub" libraries needed to bind an application to a DLL at link time. So, one should always look to see if a *.LIB file has a same-named *.DLL file; if not, chances are good that *.LIB file is a static library archive, and not export binding metadata for a DLL.