ls.ext | Deichman Library System Extended

 by   digibib Java Updated: 10 months ago - 0.7.4 License: MIT

Download this library from

Build Applications

kandi X-RAY | ls.ext REVIEW AND RATINGS

Library system developed by and for Deichman (Oslo public library). The system has been running in production since October 2016. You can view [Deichmans public website](https://sok.deichman.no) or check out the [documentation](https://github.com/digibib/ls.ext/wiki) for information about the different components, as well as setup and development guides.

kandi-support
Support

  • ls.ext has a low active ecosystem.
  • It has 32 star(s) with 5 fork(s).
  • It had no major release in the last 12 months.
  • On average issues are closed in 189 days.
  • It has a neutral sentiment in the developer community.

quality kandi
Quality

  • ls.ext has 0 bugs and 0 code smells.

security
Security

  • ls.ext has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • ls.ext code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.

license
License

  • ls.ext is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.

build
Reuse

  • ls.ext releases are available to install and integrate.
  • ls.ext has no build file. You will be need to create the build yourself to build the component from source.
  • ls.ext saves you 13615 person hours of effort in developing the same functionality from scratch.
  • It has 27320 lines of code, 1396 functions and 572 files with 0 % test coverage
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
Top functions reviewed by kandi - BETA

kandi has reviewed ls.ext and discovered the below as its top functions. This is intended to give you an instant insight into ls.ext implemented functionality, and help decide if they suit your requirements.

  • Map a Record to a Map
  • Retrieves a query of resource relationships
  • Generate MARC record for a given publication
  • Sets up the main web app .
  • Find the named name in the alphabetical order .
  • Map items to a Model .
  • Returns all labels for a given entity type .
  • Performs the CORS request
  • Compares this record to another record .
  • Builds the URI .

ls.ext Key Features

Deichman Library System - Extended

ls.ext examples and code snippets

  • commands of the music bot discord.py
  • File type from buffer using file-type
  • Preventing SQL injection in PHP Code (code included)
  • Extract words with different lengths from vector
  • How to group a bunch of string's elements
  • Json representation not showing for newly added nested components
  • Failed to resolve: com.android.support.test.espresso:espresso-intents:27.0.2
  • Undefined symbols when trying to use Cython Extensions
  • Issue with MySQL database connection after importing it
  • Attempting to make first database config in hibernate with Spring Annoations

commands of the music bot discord.py

async def on_voice_state_update(member, prev, cur):
    if client.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(client.voice_clients, channel=prev.channel)
        if channel:
            await channel.disconnect()

@client.command()
async def join(ctx):
    v_channel = ctx.message.author.voice.channel
    if v_channel:
        await v_channel.connect()

@client.command()
async def leave(ctx):
    player = ctx.message.guild.voice_client
    if player:
        await player.disconnect()
-----------------------
@client.event
async def on_voice_state_update(member, prev, cur):
    if prev.channel is not None and client.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(client.voice_clients, channel=prev.channel)
        await channel.disconnect()
@client.command()
async def leave(ctx):
    player = ctx.message.guild.voice_client
    if player is not None:
        await player.disconnect()
-----------------------
@client.event
async def on_voice_state_update(member, prev, cur):
    if prev.channel is not None and client.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(client.voice_clients, channel=prev.channel)
        await channel.disconnect()
@client.command()
async def leave(ctx):
    player = ctx.message.guild.voice_client
    if player is not None:
        await player.disconnect()

File type from buffer using file-type

await fileType.fromBuffer(buffer)
await fileType(buffer)
-----------------------
await fileType.fromBuffer(buffer)
await fileType(buffer)

Preventing SQL injection in PHP Code (code included)

$institution = $request['inst']??'';

$start = $request['start'];
$end = $request['end'];
$joins = [
    1 => ['date_field' => 'meeting_set_first', 'is_active' => false],
    2 => ['date_field' => 'occurred_date', 'is_active' => true],
    3 => ['date_field' => 'not_show_date', 'is_active' => true],
    4 => ['date_field' => 'cancel_meeting_date', 'is_active' => true],
    5 => ['date_field' => 'sale_date', 'is_active' => true],
    6 => ['date_field' => 'cancel_sale_date', 'is_active' => true],
    7 => ['date_field' => 'extended_date', 'is_active' => false],
    8 => ['date_field' => 'meeting_set_date', 'is_active' => true],
];

$sql = 'SELECT 0 as type ,ll.id as lead_name, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM customers ll LEFT JOIN leads_statistics ls  ON ll.id = ls.lead_id LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE '.($institution?" ll.inst_id = :inst0 AND ":'').' ll.created_at BETWEEN :start0 AND :end0 UNION ';
if ($institution) {
    $placeHolders[':inst0'] = $institution;
}
$placeHolders[':start0'] = $start;
$placeHolders[':end0'] = $end;

$queryJoin = [];
foreach($joins as $key => $join) {
    $queryJoin[] = 'SELECT '.$key.' as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE '.($institution?" ll.inst_id = :inst$key AND ":'').($join['is_active']?' ls.is_active = 1 AND ':'').' ls.'.$join['date_field'] ." BETWEEN :start$key AND :end$key";
    if ($institution) {
        $placeHolders[':inst'.$key] = $institution;
    }
    $placeHolders[':start'.$key] = $start;
    $placeHolders[':end'.$key] = $end;
}

$sql .= implode(' UNION ', $queryJoin);

$leads = DB::select($sql, $placeHolders);

Extract words with different lengths from vector

sub(".*-(.*)\\.out$", "\\1", x)
#[1] "DailyMean" "Peak"      "DailyMean" "Peak"  
unlist(qdapRegex::ex_between(x, "-", ".out")) 
x <- c("01611500-DailyMean.out", "01611500-Peak.out", "03180500-DailyMean.out", 
       "03180500-Peak.out")
-----------------------
sub(".*-(.*)\\.out$", "\\1", x)
#[1] "DailyMean" "Peak"      "DailyMean" "Peak"  
unlist(qdapRegex::ex_between(x, "-", ".out")) 
x <- c("01611500-DailyMean.out", "01611500-Peak.out", "03180500-DailyMean.out", 
       "03180500-Peak.out")
-----------------------
sub(".*-(.*)\\.out$", "\\1", x)
#[1] "DailyMean" "Peak"      "DailyMean" "Peak"  
unlist(qdapRegex::ex_between(x, "-", ".out")) 
x <- c("01611500-DailyMean.out", "01611500-Peak.out", "03180500-DailyMean.out", 
       "03180500-Peak.out")

How to group a bunch of string's elements

from collections import Counter
text= "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"
C = Counter(text.split('Hotel_Rooms: ')[1].split(','))
print [[k,]*v for k,v in C.items()]
-----------------------
from collections import defaultdict

s = "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

# Split rooms from 'Hotel_Rooms'
_, rooms = s.split(':')

# Group rooms into dictionary
room_dict = defaultdict(list)
for room in rooms.strip().split(','):
    room_dict[room].append(room)

print(list(room_dict.values()))
# [['R15', 'R15'], ['R11'], ['R5', 'R5', 'R5', 'R5'], ['R4', 'R4', 'R4', 'R4'], ['R8', 'R8'], ['R2', 'R2', 'R2', 'R2'], ['R3', 'R3', 'R3', 'R3'], ['R6', 'R6', 'R6', 'R6'], ['R1', 'R1', 'R1', 'R1']]
-----------------------
from itertools import groupby

string = "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

# convert string to sorted list
vals = sorted([x.strip() for x in string.split(':')[1].split(',')])

print([list(g) for k,g in groupby(vals)])

[['R1', 'R1', 'R1', 'R1'], ['R11'], ['R15', 'R15'], ['R2', 'R2', 'R2', 'R2'], ['R3', 'R3', 'R3', 'R3'], ['R4', 'R4', 'R4', 'R4'], ['R5', 'R5', 'R5', 'R5'], ['R6', 'R6', 'R6', 'R6'], ['R8', 'R8']]

Json representation not showing for newly added nested components

this.adressForm = this._fb.group({
   street: [''],
   postcode: [''],
   extraspaces: this._fb.array([])
});
initAddress() {
    return this._fb.group({
        street: ['', Validators.required],
        postcode: [''],
        extraspaces: this._fb.array([])
    });
}
extraspaces: this._fb.array([this.initextraField()])
-----------------------
this.adressForm = this._fb.group({
   street: [''],
   postcode: [''],
   extraspaces: this._fb.array([])
});
initAddress() {
    return this._fb.group({
        street: ['', Validators.required],
        postcode: [''],
        extraspaces: this._fb.array([])
    });
}
extraspaces: this._fb.array([this.initextraField()])
-----------------------
this.adressForm = this._fb.group({
   street: [''],
   postcode: [''],
   extraspaces: this._fb.array([])
});
initAddress() {
    return this._fb.group({
        street: ['', Validators.required],
        postcode: [''],
        extraspaces: this._fb.array([])
    });
}
extraspaces: this._fb.array([this.initextraField()])

Failed to resolve: com.android.support.test.espresso:espresso-intents:27.0.2

androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'
androidTestCompile 'com.android.support.test:runner:1.0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'

Undefined symbols when trying to use Cython Extensions

_ZN9TestClassC2Ev: //Constructor of the BaseObject-constructor
.LFB3:
    ...
    ret
.LFE3:
    ..
    .globl  _ZN9TestClassC1Ev
    .set    _ZN9TestClassC1Ev,_ZN9TestClassC2Ev //HERE WE GO, Complete Object constructor which we use normally

Issue with MySQL database connection after importing it

GRANT ALL ON DATABASE.* TO 'user'@'localhost';

Attempting to make first database config in hibernate with Spring Annoations

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
spring.datasource.jpa.generate-ddl=true
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    // Can be empty or you can more queries like findByXXX().
}
-----------------------
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker
spring.datasource.username=springstudent
spring.datasource.password=springstudent
spring.datasource.jpa.generate-ddl=true
public interface CustomerRepository extends JpaRepository<Customer, Long> {
    // Can be empty or you can more queries like findByXXX().
}

COMMUNITY DISCUSSIONS

Top Trending Discussions on ls.ext
  • commands of the music bot discord.py
  • File type from buffer using file-type
  • Preventing SQL injection in PHP Code (code included)
  • Cython vs Python benchmark
  • Extract words with different lengths from vector
  • How to group a bunch of string's elements
  • tkinter execution dies after about 140 iterations with no error message (mem leak?)
  • spring boot wont connect to MYSQL database using Intellij
  • Getting error of Gradle sync failed
  • Json representation not showing for newly added nested components
Top Trending Discussions on ls.ext

QUESTION

commands of the music bot discord.py

Asked 2020-Nov-18 at 02:16

When I try to run the leave and play command I get this error. I've been looking for some questions for a long time but I haven't found this error anywhere how can I fix it?

WARNING! All codes and errors have been updated on 17/11/2020 03.24 CET. If you want to check what was written before go to the edit

Join and Leave Code:

@client.command()
async def join(ctx):
    v_channel = ctx.message.author.voice.channel
    print(v_channel)
    if v_channel:
        await v_channel.connect()

@client.command()
async def leave(ctx):
    player = ctx.message.guild.voice_client
    print(player)
    if player is not None:
        await player.disconnect()

I put print () to see what was coming out of me. Join works (in fact it finds the channel and enters) when I leave it gives me the variable but first it gives me an error. Then there is a Timeout error which automatically makes the bot exit the call but it is not important.

🔊Chiamate Generali 1🔊 #print(v_channel)
Task exception was never retrieved
future: <Task finished name='Task-16' coro=<VoiceClient._create_socket() done, defined at C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py:172> exception=gaierror(11001, 'getaddrinfo failed')>
Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py", line 191, in _create_socket
    self.endpoint_ip = socket.gethostbyname(self.endpoint)
socket.gaierror: [Errno 11001] getaddrinfo failed
<discord.voice_client.VoiceClient object at 0x05BE5658> #print(player)
Ignoring exception in command join:
Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/PC GIUSEPPE/PycharmProjects/LMIIBot Development/LMIIBot Development.py", line 41, in join
    await v_channel.connect()
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\abc.py", line 1080, in connect
    await voice.connect(reconnect=reconnect)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py", line 218, in connect
    await self.start_handshake()
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py", line 154, in start_handshake
    await asyncio.wait_for(self._handshake_complete.wait(), timeout=self.timeout)
  File "C:\Users\PC GIUSEPPE\AppData\Local\Programs\Python\Python38-32\lib\asyncio\tasks.py", line 490, in wait_for
    raise exceptions.TimeoutError()
asyncio.exceptions.TimeoutError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TimeoutError: 

code on_voice_state_update:

@client.event
async def on_voice_state_update(member, prev, cur):
    print(member)
    print(prev)
    print(cur)
    if prev.channel is not None and client.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(client.voice_clients, channel=prev.channel)
        print(channel)
        await channel.disconnect()

I did the same thing with the commands above. Here are the errors:

LMII Bot Development#9553 #print(member)
<VoiceState self_mute=False self_deaf=False self_stream=False channel=None> #print(prev)
<VoiceState self_mute=False self_deaf=False self_stream=False channel=<VoiceChannel id=638017907791626250 name='🔊Chiamate Generali 1🔊' position=14 bitrate=128000 user_limit=0 category_id=637626960599842825>> #print(cur)
Task exception was never retrieved
future: <Task finished name='Task-15' coro=<VoiceClient._create_socket() done, defined at C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py:172> exception=gaierror(11001, 'getaddrinfo failed')>
Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\voice_client.py", line 191, in _create_socket
    self.endpoint_ip = socket.gethostbyname(self.endpoint)
socket.gaierror: [Errno 11001] getaddrinfo failed
Peppe Grasso#9737 #print(member)
<VoiceState self_mute=False self_deaf=False self_stream=False channel=<VoiceChannel id=638017907791626250 name='🔊Chiamate Generali 1🔊' position=14 bitrate=128000 user_limit=0 category_id=637626960599842825>> #print(prev)
<VoiceState self_mute=False self_deaf=False self_stream=False channel=None> print(cur)
<discord.voice_client.VoiceClient object at 0x05454670> print(channel)

Play code:

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}

def endSong(guild, path):
    os.remove(path)

@client.command(pass_context=True)
async def play(ctx, url):
    if not ctx.message.author.voice:
        await ctx.send('You are not connected to a voice channel') #message when you are not connected to any voice channel
        return

    else:
        channel = ctx.message.author.voice.channel
    print(channel)
    voice_client = await channel.connect()
    print(voice_client)
    guild = ctx.message.guild

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        file = ydl.extract_info(url, download=True)
        path = str(file['title']) + "-" + str(file['id'] + ".mp3")

    voice_client.play(discord.FFmpegPCMAudio(path), after=lambda x: endSong(guild, path))
    voice_client.source = discord.PCMVolumeTransformer(voice_client.source, 1)

    await ctx.send(f'**Music: **{url}') #sends info about song playing right now

Error:

ERROR: MYAKzSEKe-g: YouTube said: Unable to extract video data
Ignoring exception in command play:
Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 797, in extract_info
    ie_result = ie.extract(url)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\extractor\common.py", line 532, in extract
    ie_result = self._real_extract(url)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\extractor\youtube.py", line 1909, in _real_extract
    raise ExtractorError(
youtube_dl.utils.ExtractorError: MYAKzSEKe-g: YouTube said: Unable to extract video data

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/PC GIUSEPPE/PycharmProjects/LMIIBot Development/LMIIBot Development.py", line 80, in play
    file = ydl.extract_info(url, download=True)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 820, in extract_info
    self.report_error(compat_str(e), e.format_traceback())
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 625, in report_error
    self.trouble(error_message, tb)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 595, in trouble
    raise DownloadError(message, exc_info)
youtube_dl.utils.DownloadError: ERROR: MYAKzSEKe-g: YouTube said: Unable to extract video data

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\PC GIUSEPPE\PycharmProjects\LMIIBot Development\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: DownloadError: ERROR: MYAKzSEKe-g: YouTube said: Unable to extract video data

ANSWER

Answered 2020-Nov-15 at 23:18

Please don't allow none values into the function

async def on_voice_state_update(member, prev, cur):
    if client.user in prev.channel.members and len([m for m in prev.channel.members if not m.bot]) == 0:
        channel = discord.utils.get(client.voice_clients, channel=prev.channel)
        if channel:
            await channel.disconnect()

@client.command()
async def join(ctx):
    v_channel = ctx.message.author.voice.channel
    if v_channel:
        await v_channel.connect()

@client.command()
async def leave(ctx):
    player = ctx.message.guild.voice_client
    if player:
        await player.disconnect()

Source https://stackoverflow.com/questions/64734773

QUESTION

File type from buffer using file-type

Asked 2020-Jan-11 at 10:45

I tried finding type of file using file-type module but when i try to run it gives me error that "error:.... fileType.fromBuffer is not a function.

`

const fileType = require('file-type');
const readChunk = require('read-chunk');
exports.ext = async function(file) {
const buffer = readChunk.sync(file, 0, 512)
let type = await fileType.fromBuffer(buffer);
console.log("type of file",type)
return value

`

this is in utils.js file and i am calling it in other type.js file

`

var extension =  await utils.ext('ABC.png')
 console.log(extension)

`

Can anybody tell me what should i do?

ANSWER

Answered 2020-Jan-11 at 10:45

seems like there is a miss in npm documentation for the module file-type. The error which you are getting means the module doesn't expose such a method(fromBuffer).

the fileType accepts buffer as an input i.e. replace

await fileType.fromBuffer(buffer)

with

await fileType(buffer)

kindly follow this file from the module source

Source https://stackoverflow.com/questions/59692545

QUESTION

Preventing SQL injection in PHP Code (code included)

Asked 2019-Dec-25 at 15:37

First timer here, so I'll try to be as thorough as possible.

I'm a rather new programmer and started working at a new company where I've been attempting to prevent some SQL injection in a specific piece of PHP code that was leftover from an old project, but is needed in my rewrite of it.

This project is in Laravel as a backend and AngularJS as the frontend.

I've attempted several ways to prevent the SQL injection but have gotten the same error in all of them.

Error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'll.created_at BETWEEN '?' AND '?' UNION SELECT 1 as type, ll.id, ll.name, ll.ema' at line 1

Here is the original code in question:

   if (!empty($request['inst'])) {
        $institution = $request['inst'];
        $inst = ' ll.inst_id = ' . $request['inst'] . ' AND ';
        $instCount = ' customers.inst_id = :inst AND ';
        $instEvent = ' location_id = :inst AND ';
    } else {
        $inst = ' ';
        $instCount = ' ';
        $instEvent = ' ';
        $institution = "";
    }
    $startTime = $request['start'];
    $endTime = $request['end'];

$sql = " SELECT 0 as type ,ll.id as lead_name, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM customers ll LEFT JOIN leads_statistics ls  ON ll.id = ls.lead_id"
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ll.created_at BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 1 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.meeting_set_first BETWEEN '" . $request['start'] . "' AND '" . $request['end']  
            . "' UNION SELECT 2 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.occurred_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 3 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.not_show_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 4 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.cancel_meeting_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 5 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.sale_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 6 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.cancel_sale_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 7 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.extended_date BETWEEN '" . $request['start'] . "' AND '" . $request['end']
            . "' UNION SELECT 8 as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id "
            . " LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE $inst ls.is_active = 1 AND ls.meeting_set_date BETWEEN '" . $request['start'] . "' AND '" . $request['end'] . "'";

$leads = DB::select($sql);

Here are some of the techniques I've used after perusing the internet and SO at length.

  1. Placeholders (? instead of all the variables and creating an array at the end with all the variables 9 times over)
  2. Named Bindings example: DB::select($sql, ["inst" => $institution, "start" => $startTime, "end" => $endTime,])
  3. Named bindings Named bindings with PDO::ATTR_EMULATE_PREPARES => true, so I can use :inst, :start, :end multiple times
  4. SQL variable bindings with @ symbols

Results of techniques:

  1. No protection - works fine, I receive the proper results
  2. Placeholders - I get the above error, but the SQL has the proper data in the placeholders. I can take the resulting SQL and run it through the phpmyadmin server SQL query and I receive the data as expected.
  3. Named Bindings - Doesn't work at all. I get an error stating SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
  4. Named Bindings withPDO::ATTR_EMULATE_PREPARES => true, - works, however it affects all the data I then pull from my server turning things such as numbers to strings or worse. This plays havoc with typing all over the place
  5. SQL variable binding - didn't work either, received the above error

I am unsure if it's possible to turn this giant SQL query into Laravel Eloquent or Query Builder, though I have tried.

Anyone have any ideas? Any help would be immensely appreciated, I've been wrestling with this for a few weeks now.

ANSWER

Answered 2019-Dec-25 at 15:15
$institution = $request['inst']??'';

$start = $request['start'];
$end = $request['end'];
$joins = [
    1 => ['date_field' => 'meeting_set_first', 'is_active' => false],
    2 => ['date_field' => 'occurred_date', 'is_active' => true],
    3 => ['date_field' => 'not_show_date', 'is_active' => true],
    4 => ['date_field' => 'cancel_meeting_date', 'is_active' => true],
    5 => ['date_field' => 'sale_date', 'is_active' => true],
    6 => ['date_field' => 'cancel_sale_date', 'is_active' => true],
    7 => ['date_field' => 'extended_date', 'is_active' => false],
    8 => ['date_field' => 'meeting_set_date', 'is_active' => true],
];

$sql = 'SELECT 0 as type ,ll.id as lead_name, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM customers ll LEFT JOIN leads_statistics ls  ON ll.id = ls.lead_id LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE '.($institution?" ll.inst_id = :inst0 AND ":'').' ll.created_at BETWEEN :start0 AND :end0 UNION ';
if ($institution) {
    $placeHolders[':inst0'] = $institution;
}
$placeHolders[':start0'] = $start;
$placeHolders[':end0'] = $end;

$queryJoin = [];
foreach($joins as $key => $join) {
    $queryJoin[] = 'SELECT '.$key.' as type, ll.id, ll.name, ll.email, ll.updated_at, u.employee_name, ls.meeting_set_date, ls.meeting_set_first FROM leads_statistics ls LEFT JOIN customers ll ON ls.lead_id = ll.id LEFT JOIN users u ON ll.userUpdate = u.employee_id  WHERE '.($institution?" ll.inst_id = :inst$key AND ":'').($join['is_active']?' ls.is_active = 1 AND ':'').' ls.'.$join['date_field'] ." BETWEEN :start$key AND :end$key";
    if ($institution) {
        $placeHolders[':inst'.$key] = $institution;
    }
    $placeHolders[':start'.$key] = $start;
    $placeHolders[':end'.$key] = $end;
}

$sql .= implode(' UNION ', $queryJoin);

$leads = DB::select($sql, $placeHolders);

Source https://stackoverflow.com/questions/59479078

QUESTION

Cython vs Python benchmark

Asked 2019-Sep-11 at 12:07

I'm trying to get a benchmark from cython vs pure python with bubble sort algorithm, and this is my result, that shows me pure python is faster than cython is my result correct or something is wrong with my code?

The script tries to create a random list and then try to sort it with bubble sort algorithm in cython and pure python.

benchmark.py

import cybubble
import pybubble
from timeit import default_timer as timer
from decimal import *
import random
getcontext().prec = 8

if __name__ == '__main__':
    random_list = [random.randrange(0,10) for i in range(9999)] #generate a random list
    cy_start = timer()   #start timer
    cybubble.bubble_sort(random_list)   #execute cython bubble sort
    cy_end = timer()     #stop timer

    py_start = timer()   #start timer
    pybubble.bubble_sort(random_list)   #execute pure python bubble sort
    py_end = timer()     #stop time

    print "Python execution time:"
    python = (Decimal(py_end) - Decimal(py_start))
    print (python)

    print "Cython execution time:"
    cython = (Decimal(cy_end) - Decimal(cy_start))
    print (cython)

cybubble.pyx

cpdef bubble_sort(collection):
    cdef int length
    cdef int i
    cdef int j
    length = len(collection)
    for i in range(length-1):
        swapped = False
        for j in range(length-1-i):
            if collection[j] > collection[j+1]:
                swapped = True
                collection[j], collection[j+1] = collection[j+1], collection[j]
        if not swapped:
            break  # Stop iteration if the collection is sorted.
    return collection

pybubble.py

def bubble_sort(collection):
    length = len(collection)
    for i in range(length-1):
        swapped = False
        for j in range(length-1-i):
            if collection[j] > collection[j+1]:
                swapped = True
                collection[j], collection[j+1] = collection[j+1], collection[j]
        if not swapped:
            break  # Stop iteration if the collection is sorted.
    return collection

setup.py

# several files with ext .pyx, that i will call by their name
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

ext_modules=[
    Extension("cybubble",       ["cybubble.pyx"]),
]

setup(
  name = 'MyProject',
  cmdclass = {'build_ext': build_ext},
  ext_modules = ext_modules,
)

command to compile the cython module: python setup.py build_ext --inplace

result:

Python execution time:
0.0014050007
Cython execution time:
1.5976260

The result shows me that the pure python is faster than cython in this example and cython is not always faster than pure python.

I expect better performance for cython than pure python in this script.

This is how i SOLVED my problem in benchmark.py

import cybubble
import pybubble
from timeit import default_timer as timer
from decimal import *
import random
import copy
getcontext().prec = 8

if __name__ == '__main__':
    random_list = [random.randrange(0,10) for i in range(9999)]
    random_list2 = copy.copy(random_list)
    random_list3 = copy.copy(random_list)


    cy_start = timer()
    cybubble.bubble_sort(random_list2)
    cy_end = timer()

    py_start = timer()
    pybubble.bubble_sort(random_list3)
    py_end = timer()


    print "Python execution time:"
    python = (Decimal(py_end) - Decimal(py_start))
    print (python)

    print "Cython execution time:"
    cython = (Decimal(cy_end) - Decimal(cy_start))
    print (cython)

Result:

Python execution time:
8.9958801
Cython execution time:
1.6466939

ANSWER

Answered 2019-Sep-11 at 11:34

This is because you sort the list in-place--you sort the list with Cython first, when the list is randomized, and then sort the list with Python, when the list is already sorted. Since bubble sort has a best-case time complexity of O(n) when the list is already sorted, the call to the Python's version, when the list is already sorted, is magnitudes faster than the call to the Cython's version, when the list is randomized, which takes an average time complexity of O(n ^ 2).

You should sort copies of the list if you would like to benchmark the two implementations properly.

Source https://stackoverflow.com/questions/57887685

QUESTION

Extract words with different lengths from vector

Asked 2019-Sep-10 at 00:47

I have two types of results which are differentiated with the words DailyMean and Peak. I would like to extract the words DailyMean and Peak from filenames.

    filenames  <- list.files(path = folder.out, pattern = 
    ls.extensions[[T]][type])
    "01611500-DailyMean.out" "01611500-Peak.out"      
    "03180500-DailyMean.out" "03180500-Peak.out"

Used substr and regexec but could only extract a fixed length
    "Dail" "Peak" "Dail" "Peak"

The result should be as follows
    "DailyMean" "Peak" "DailyMean" "Peak"

ANSWER

Answered 2019-Sep-10 at 00:47

We could use sub to extract everything between a hyphen and ".out".

sub(".*-(.*)\\.out$", "\\1", x)
#[1] "DailyMean" "Peak"      "DailyMean" "Peak"  

We can also use qdapRegex::ex_between which does the same thing with no regex

unlist(qdapRegex::ex_between(x, "-", ".out")) 

data

x <- c("01611500-DailyMean.out", "01611500-Peak.out", "03180500-DailyMean.out", 
       "03180500-Peak.out")

Source https://stackoverflow.com/questions/57862646

QUESTION

How to group a bunch of string's elements

Asked 2018-Dec-20 at 16:05

I have a string like:

"Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"

and I am trying to make a list of list of those which are the same. This is my code:

List = []
ls = []
for el in input:
  if el == 'Hotel_Rooms: ':
      pass
  else:
    if el !=',': 
      ls.extend(el)
    else:
      List.append(ls)
print List

But the result is so weird. Could you please lemme know how can I improve my code?

Thanks

ANSWER

Answered 2018-Dec-20 at 16:05

Try to use collections.Counter, as follows:

from collections import Counter
text= "Hotel_Rooms: R15,R11,R5,R4,R8,R2,R15,R3,R6,R1,R6,R5,R3,R2,R4,R1,R2,R5,R1,R4,R3,R6,R8,R4,R3,R1,R5,R6,R2"
C = Counter(text.split('Hotel_Rooms: ')[1].split(','))
print [[k,]*v for k,v in C.items()]

Source https://stackoverflow.com/questions/53868208

QUESTION

tkinter execution dies after about 140 iterations with no error message (mem leak?)

Asked 2018-Nov-29 at 20:08

My code dies after about 140+ iterations, and I don't know why. I guess memory leak is a possibility, but I couldn't find it. I also found out that changing some arithmetic constants can prolong the time until the crash.

I have a genetic algorithm that tries to find best (i.e. minimal steps) route from point A (src) to point B (dst).

I create a list of random chromosomes, where each chromosome has:

  1. src + dst [always the same]
  2. list of directions (random)

I then run the algorithm:

  1. find best route and draw it (for visualization purposes)
  2. Given a probability P - replace the chromosomes with cross-overs (i.e. pick 2, and take the "end" of one's directions, and replace the "end" of the second's)
  3. Given probability Q - mutate (replace the next direction with a random direction)

This all goes well, and most of the times I do find a route (usually not the ideal one), but sometimes, when it searches for a long time (say, about 140+ iterations) it just crushes. No warning. No error.

How can I prevent that (a simple iteration limit can work, but I do want the algorithm to run for a long time [~2000+ iterations])?

I think the relevant parts of the code are:

  1. update function inside GUI class
  2. which calls to cross_over
  3. When playing with the update_fitness() score values (changing score -= (weight+1)*2000*(shift_x + shift_y) to score -= (weight+1)*2*(shift_x + shift_y) it runs for a longer time. Could be some kind of an arithmetic overflow?

import tkinter as tk
from enum import Enum
from random import randint, sample
from copy import deepcopy
from time import sleep
from itertools import product


debug_flag = False

class Direction(Enum):
    Up      = 0
    Down    = 1
    Left    = 2
    Right   = 3

    def __str__(self):
        return str(self.name)

    def __repr__(self):
        return str(self.name)[0]

# A chromosome is a list of directions that should lead the way from src to dst.
# Each step in the chromosome is a direction (up, down, right ,left)
# The chromosome also keeps track of its route
class Chromosome:   
    def __init__(self, src = None, dst = None, length = 10, directions = None):
        self.MAX_SCORE = 1000000

        self.route = [src]
        if not directions:
            self.directions = [Direction(randint(0,3)) for i in range(length)]
        else:
            self.directions = directions
        self.src = src
        self.dst = dst
        self.fitness = self.MAX_SCORE

    def __str__(self):
        return str(self.fitness)

    def __repr__(self):
        return self.__str__()

    def set_src(self, pixel):
        self.src = pixel

    def set_dst(self, pixel):
        self.dst = pixel

    def set_directions(self, ls):
        self.directions = ls

    def update_fitness(self):
        # Higher score - a better fitness
        score = self.MAX_SCORE - len(self.route)

        score += 4000*(len(set(self.route)) - len(self.route))  # penalize returning to the same cell
        score += (self.dst in self.route) * 500                 # bonus routes that get to dst

        for weight,cell in enumerate(self.route):
            shift_x = abs(cell[0] - self.dst[0])
            shift_y = abs(cell[1] - self.dst[1])
            score -= (weight+1)*2000*(shift_x + shift_y)        # penalize any wrong turn

        self.fitness = max(score, 0)

    def update(self, mutate_chance = 0.9):
        # mutate #
        self.mutate(chance = mutate_chance)

        # move according to direction
        last_cell = self.route[-1]

        try:
            direction = self.directions[len(self.route) - 1]
        except IndexError:
            print('No more directions. Halting')
            return

        if  direction == Direction.Down:
            x_shift, y_shift =  0,  1
        elif direction == Direction.Up:
            x_shift, y_shift =  0, -1
        elif direction == Direction.Left:
            x_shift, y_shift = -1,  0
        elif direction == Direction.Right:
            x_shift, y_shift =  1,  0

        new_cell = last_cell[0] + x_shift, last_cell[1] + y_shift
        self.route.append(new_cell)
        self.update_fitness()


    def cross_over(p1, p2, loc = None):
        # find the cross_over point
        if not loc:
            loc = randint(0,len(p1.directions))

        # choose one of the parents randomly
        x = randint(0,1)
        src_parent = (p1, p2)[x]
        dst_parent = (p1, p2)[1 - x]
        son = deepcopy(src_parent)
        son.directions[loc:] = deepcopy(dst_parent.directions[loc:])

        return son   

    def mutate(self, chance = 1):
        if 100*chance > randint(0,99):
            self.directions[len(self.route) - 1] = Direction(randint(0,3))




class GUI:
    def __init__(self, rows = 10, cols = 10, iteration_timer = 100, chromosomes = [], cross_over_chance = 0.5, mutation_chance = 0.3, MAX_ITER = 100):        

        self.rows = rows
        self.cols = cols
        self.canv_w = 800
        self.canv_h = 800
        self.cell_w = self.canv_w // cols
        self.cell_h = self.canv_h // rows

        self.master = tk.Tk()
        self.canvas = tk.Canvas(self.master, width = self.canv_w, height = self.canv_h)       
        self.canvas.pack()

        self.rect_dict          = {}
        self.iteration_timer    = iteration_timer
        self.iterations         = 0
        self.MAX_ITER           = MAX_ITER

        self.chromosome_list = chromosomes
        self.src             = chromosomes[0].src # all chromosomes share src + dst
        self.dst             = chromosomes[0].dst

        self.prev_best_route    = []
        self.cross_over_chance  = cross_over_chance
        self.mutation_chance    = mutation_chance
        self.no_obstacles       = True

        # init grid #
        for r in range(rows):
            for c in range(cols):
                self.rect_dict[(r, c)] = self.canvas.create_rectangle(r    *self.cell_h, c    *self.cell_w,
                                                                      (1+r)*self.cell_h, (1+c)*self.cell_w,
                                                                      fill="gray")
        # init grid #

        # draw src + dst #
        self.color_src_dst()
        # draw src + dst #

        # after + mainloop #
        self.master.after(iteration_timer, self.start_gui)
        tk.mainloop()
        # after + mainloop #

    def start_gui(self):
        self.start_msg = self.canvas.create_text(self.canv_w // 2,3*self.canv_h // 4, fill = "black", font = "Times 25 bold underline", 
                                text="Starting new computation.\nPopulation size = %d\nCross-over chance = %.2f\nMutation chance = %.2f" %
                                (len(self.chromosome_list), self.cross_over_chance, self.mutation_chance))
        self.master.after(2000, self.update)

    def end_gui(self, msg="Bye Bye!"):
        self.master.wm_attributes('-alpha', 0.9) # transparency
        self.canvas.create_text(self.canv_w // 2,3*self.canv_h // 4, fill = "black", font = "Times 25 bold underline", text=msg)

        cell_ls = []
        for idx,cell in enumerate(self.prev_best_route):
            if cell in cell_ls:
                continue
            cell_ls.append(cell)
            self.canvas.create_text(cell[0]*self.cell_w, cell[1]*self.cell_h, fill = "purple", font = "Times 16 bold italic", text=str(idx+1))


        self.master.after(3000, self.master.destroy)

    def color_src_dst(self):
        r_src = self.rect_dict[self.src]
        r_dst = self.rect_dict[self.dst]
        c_src = 'blue'
        c_dst = 'red'
        self.canvas.itemconfig(r_src, fill=c_src)
        self.canvas.itemconfig(r_dst, fill=c_dst)

    def color_route(self, route, color):
        for cell in route:
            try:
                self.canvas.itemconfig(self.rect_dict[cell], fill=color)
            except KeyError:
                # out of bounds -> ignore
                continue

        # keep the src + dst
        self.color_src_dst()
        # keep the src + dst

    def compute_shortest_route(self):
        if self.no_obstacles:
            return (1 + 
                    abs(self.chromosome_list[0].dst[0] - self.chromosome_list[0].src[0]) + 
                    abs(self.chromosome_list[0].dst[1] - self.chromosome_list[0].src[1]))
        else:
            return 0

    def create_weighted_chromosome_list(self):
        ls = []
        for ch in self.chromosome_list:
            tmp = [ch] * (ch.fitness // 200000)
            ls.extend(tmp)
        return ls

    def cross_over(self):
        new_chromosome_ls = []
        weighted_ls = self.create_weighted_chromosome_list()

        while len(new_chromosome_ls) < len(self.chromosome_list):
            try:
                p1, p2 = sample(weighted_ls, 2)
                son = Chromosome.cross_over(p1, p2)
                if son in new_chromosome_ls:
                    continue
                else:
                    new_chromosome_ls.append(son)
            except ValueError:
                continue

        return new_chromosome_ls

    def end_successfully(self):
        self.end_gui(msg="Got to destination in %d iterations!\nBest route length = %d" % (len(self.prev_best_route), self.compute_shortest_route()))

    def update(self): 
        # first time #
        self.canvas.delete(self.start_msg)
        # first time #

        # end #
        if self.iterations >= self.MAX_ITER:
            self.end_gui()
            return
        # end #

        # clean the previously best chromosome route #
        self.color_route(self.prev_best_route[1:], 'gray')
        # clean the previously best chromosome route #

        # cross over #
        if 100*self.cross_over_chance > randint(0,99):
            self.chromosome_list = self.cross_over()
        # cross over #

        # update (includes mutations) all chromosomes #
        for ch in self.chromosome_list:
            ch.update(mutate_chance=self.mutation_chance)
        # update (includes mutations) all chromosomes #

        # show all chromsome fitness values #
        if debug_flag:
            fit_ls = [ch.fitness for ch in self.chromosome_list]
            print(self.iterations, sum(fit_ls) / len(fit_ls), fit_ls)
        # show all chromsome fitness values #

        # find and display best chromosome #
        best_ch = max(self.chromosome_list, key=lambda ch : ch.fitness)
        self.prev_best_route = deepcopy(best_ch.route)
        self.color_route(self.prev_best_route[1:], 'gold')
        # find and display best chromosome #

        # check if got to dst #
        if best_ch.dst == best_ch.route[-1]:
            self.end_successfully()
            return
        # check if got to dst #

        # after + update iterations #
        self.master.after(self.iteration_timer, self.update)
        self.iterations += 1
        # after + update iterations #



def main():
    iter_timer, ITER = 10, 350
    r,c              = 20,20
    s,d              = (13,11), (7,8)
    population_size     = [80,160]
    cross_over_chance   = [0.2,0.4,0.5]

    for pop_size, CO_chance in product(population_size, cross_over_chance):
        M_chance = 0.7 - CO_chance
        ch_ls = [Chromosome(src=s, dst=d, directions=[Direction(randint(0,3)) for i in range(ITER)]) for i in range(pop_size)]
        g = GUI(rows=r, cols=c, chromosomes = ch_ls, iteration_timer=iter_timer, 
                cross_over_chance=CO_chance, mutation_chance=M_chance, MAX_ITER=ITER-1)
        del(ch_ls)
        del(g)

if __name__ == "__main__":
    main()

ANSWER

Answered 2018-Nov-29 at 18:02

I do not know if you know the Python Profiling tool of Visual Studio, but it is quite useful in cases as yours (though I usually program with editors, like VS Code).

I have run your program and, as you said, it sometimes crashes. I have analyzed the code with the profiling tool and it seems that the problem is the function cross_over, specifically the random function:

enter image description here

enter image description here

I would strongly suggest reviewing your cross_over and mutation functions. The random function should not be called so many times (2 millions).

I have previously programmed Genetic Algorithms and, to me, it seems that your program is falling into a local minimum. What is suggested in these cases is playing with the percentage of mutation. Try to increase it a little bit so that you could get out of the local minimum.

Source https://stackoverflow.com/questions/53543409

QUESTION

spring boot wont connect to MYSQL database using Intellij

Asked 2018-Sep-22 at 17:56

please help me i spended 2 days on this small problem and i don't know how to solve it yet.

i have installed mysql in a docker container in my local windows 10 PC.

mysql server is working fine (running from MySQL Workbench)

but when i try to run from intellij these error messages apear.


    "C:\Program Files\Java\jdk1.8.0_181\bin\java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.6\lib\idea_rt.jar=5500:C:\Program Files\JetBrains\IntelliJ IDEA 2017.1.6\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_181\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_181\jre\lib\rt.jar;C:\Users\lenovo\Desktop\poservice\target\classes;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.0.5.RELEASE\spring-boot-starter-data-jpa-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter\2.0.5.RELEASE\spring-boot-starter-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot\2.0.5.RELEASE\spring-boot-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.0.5.RELEASE\spring-boot-autoconfigure-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.0.5.RELEASE\spring-boot-starter-logging-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\lenovo\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\lenovo\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;C:\Users\lenovo\.m2\repository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;C:\Users\lenovo\.m2\repository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;C:\Users\lenovo\.m2\repository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;C:\Users\lenovo\.m2\repository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.0.5.RELEASE\spring-boot-starter-aop-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\aspectj\aspectjweaver\1.8.13\aspectjweaver-1.8.13.jar;C:\Users\lenovo\.m2\repository\javax\transaction\javax.transaction-api\1.2\javax.transaction-api-1.2.jar;C:\Users\lenovo\.m2\repository\org\hibernate\hibernate-core\5.2.17.Final\hibernate-core-5.2.17.Final.jar;C:\Users\lenovo\.m2\repository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;C:\Users\lenovo\.m2\repository\org\hibernate\javax\persistence\hibernate-jpa-2.1-api\1.0.2.Final\hibernate-jpa-2.1-api-1.0.2.Final.jar;C:\Users\lenovo\.m2\repository\org\javassist\javassist\3.22.0-GA\javassist-3.22.0-GA.jar;C:\Users\lenovo\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\lenovo\.m2\repository\org\jboss\jandex\2.0.3.Final\jandex-2.0.3.Final.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;C:\Users\lenovo\.m2\repository\dom4j\dom4j\1.6.1\dom4j-1.6.1.jar;C:\Users\lenovo\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.0.1.Final\hibernate-commons-annotations-5.0.1.Final.jar;C:\Users\lenovo\.m2\repository\org\springframework\data\spring-data-jpa\2.0.10.RELEASE\spring-data-jpa-2.0.10.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\data\spring-data-commons\2.0.10.RELEASE\spring-data-commons-2.0.10.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-orm\5.0.9.RELEASE\spring-orm-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-context\5.0.9.RELEASE\spring-context-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-tx\5.0.9.RELEASE\spring-tx-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-beans\5.0.9.RELEASE\spring-beans-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-aspects\5.0.9.RELEASE\spring-aspects-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.0.5.RELEASE\spring-boot-starter-jdbc-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\com\zaxxer\HikariCP\2.7.9\HikariCP-2.7.9.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-jdbc\5.0.9.RELEASE\spring-jdbc-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-security\2.0.5.RELEASE\spring-boot-starter-security-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-aop\5.0.9.RELEASE\spring-aop-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\security\spring-security-config\5.0.8.RELEASE\spring-security-config-5.0.8.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\security\spring-security-web\5.0.8.RELEASE\spring-security-web-5.0.8.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-expression\5.0.9.RELEASE\spring-expression-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.0.5.RELEASE\spring-boot-starter-web-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.0.5.RELEASE\spring-boot-starter-json-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.6\jackson-databind-2.9.6.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.6\jackson-core-2.9.6.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.6\jackson-datatype-jdk8-2.9.6.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.6\jackson-datatype-jsr310-2.9.6.jar;C:\Users\lenovo\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.6\jackson-module-parameter-names-2.9.6.jar;C:\Users\lenovo\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.0.5.RELEASE\spring-boot-starter-tomcat-2.0.5.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.34\tomcat-embed-core-8.5.34.jar;C:\Users\lenovo\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.34\tomcat-embed-el-8.5.34.jar;C:\Users\lenovo\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.34\tomcat-embed-websocket-8.5.34.jar;C:\Users\lenovo\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.12.Final\hibernate-validator-6.0.12.Final.jar;C:\Users\lenovo\.m2\repository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-web\5.0.9.RELEASE\spring-web-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-webmvc\5.0.9.RELEASE\spring-webmvc-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\mysql\mysql-connector-java\5.1.47\mysql-connector-java-5.1.47.jar;C:\Users\lenovo\.m2\repository\org\projectlombok\lombok\1.16.22\lombok-1.16.22.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-core\5.0.9.RELEASE\spring-core-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\spring-jcl\5.0.9.RELEASE\spring-jcl-5.0.9.RELEASE.jar;C:\Users\lenovo\.m2\repository\org\springframework\security\spring-security-core\5.0.8.RELEASE\spring-security-core-5.0.8.RELEASE.jar" com.darelweb.poservice.PoserviceApplication

      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.5.RELEASE)

    2018-09-22 12:25:00.839  INFO 22552 --- [           main] c.d.poservice.PoserviceApplication       : Starting PoserviceApplication on rm-lt-w10-p50 with PID 22552 (C:\Users\lenovo\Desktop\poservice\target\classes started by lenovo in C:\Users\lenovo\Desktop\poservice)
    2018-09-22 12:25:00.843  INFO 22552 --- [           main] c.d.poservice.PoserviceApplication       : No active profile set, falling back to default profiles: default
    2018-09-22 12:25:00.889  INFO 22552 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@75c072cb: startup date [Sat Sep 22 12:25:00 GMT+01:00 2018]; root of context hierarchy
    2018-09-22 12:25:01.925  INFO 22552 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$5e92af76] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
    2018-09-22 12:25:02.569  INFO 22552 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2018-09-22 12:25:02.595  INFO 22552 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2018-09-22 12:25:02.595  INFO 22552 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.34
    2018-09-22 12:25:02.599  INFO 22552 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_181\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\Docker\Docker\Resources\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Intel\Shared Libraries\redist\intel64\compiler;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\Users\lenovo\AppData\Local\Microsoft\WindowsApps;C:\Users\lenovo\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\lenovo\AppData\Roaming\npm;.]
    2018-09-22 12:25:02.705  INFO 22552 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2018-09-22 12:25:02.706  INFO 22552 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1821 ms
    2018-09-22 12:25:02.810  INFO 22552 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2018-09-22 12:25:02.811  INFO 22552 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2018-09-22 12:25:02.811  INFO 22552 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2018-09-22 12:25:02.811  INFO 22552 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2018-09-22 12:25:02.811  INFO 22552 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
    2018-09-22 12:25:02.812  INFO 22552 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2018-09-22 12:25:02.970  INFO 22552 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
    2018-09-22 12:25:04.118 ERROR 22552 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

    java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
        at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3978) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3914) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1714) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1224) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2199) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2230) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2025) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:778) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_181]
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_181]
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_181]
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_181]
        at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330) ~[mysql-connector-java-5.1.47.jar:5.1.47]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:117) ~[HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:123) ~[HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:365) ~[HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:194) ~[HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:460) [HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:534) [HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115) [HikariCP-2.7.9.jar:na]
        at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) [HikariCP-2.7.9.jar:na]
        at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151) [spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115) [spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78) [spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319) [spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356) [spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.DatabaseLookup.getDatabase(DatabaseLookup.java:72) [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.JpaProperties.determineDatabase(JpaProperties.java:166) [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.jpaVendorAdapter(JpaBaseConfiguration.java:111) [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$7d6971e5.CGLIB$jpaVendorAdapter$4() [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$7d6971e5$$FastClassBySpringCGLIB$$d9119109.invoke() [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) [spring-core-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365) [spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration$$EnhancerBySpringCGLIB$$7d6971e5.jpaVendorAdapter() [spring-boot-autoconfigure-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:818) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:474) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:724) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:474) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:333) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265) ~[spring-boot-2.0.5.RELEASE.jar:2.0.5.RELEASE]
        at com.darelweb.poservice.PoserviceApplication.main(PoserviceApplication.java:10) ~[classes/:na]

    2018-09-22 12:25:04.127  WARN 22552 --- [           main] o.s.b.a.orm.jpa.DatabaseLookup           : Unable to determine jdbc url from datasource

    org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
        at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:328) ~[spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]
        at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:356) ~[spring-jdbc-5.0.9.RELEASE.jar:5.0.9.RELEASE]

    Process finished with exit code 1

my application.proprieties file :


    spring.datasource.url = jdbc:mysql://localhost:3306/poservicedb?useSSL=false

    spring.datasource.username = root
    spring.datasource.password = pos

    spring.datasource.testWhileIdle = true
    spring.datasource.validationQuery = SELECT 1


    spring.jpa.hibernate.ddl-auto = update
    spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

my pom.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.darelweb</groupId>
    <artifactId>poservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>poservice</name>
    <description>point of sales saas application</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

ANSWER

Answered 2018-Sep-22 at 12:56

When Docker runs MySQL, you have to use 127.0.0.1 instead of localhost. This is because when a MySQL client tries to connect to localhost, it looks for the socket file descriptor instead of using TCP/IP.

It's explained in this post here: Connect to Docker MySQL container from localhost?

Source https://stackoverflow.com/questions/52456362

QUESTION

Getting error of Gradle sync failed

Asked 2018-Apr-04 at 13:57

I am getting error of

Gradle sync failed: Could not find org.jetbrains.trove4j:trove4j:20160824. Searched in the following locations: file:/D:/android/gradle/m2repository/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom file:/D:/android/gradle/m2repository/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom https://repo1.maven.org/maven2/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.pom https://maven.google.com/org/jetbrains/trove4j/trove4j/20160824/trove4j-20160824.jar Required by: project : > com.android.tools.build:gradle:3.0.1 > com.android.tools.build:gradle-core:3.0.1 > com.android.tools.lint:lint:26.0.1 > com.android.tools.lint:lint-checks:26.0.1 > com.android.tools.lint:lint-api:26.0.1 > com.android.tools.external.com-intellij:intellij-core:26.0.1 Consult IDE log for more details (Help | Show Log)

gradle-wrapper.properties

  > distributionBase=GRADLE_USER_HOME  distributionPath=wrapper/dists 
  > zipStoreBase=GRADLE_USER_HOME  zipStorePath=wrapper/dists
  > distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

build.gradle

   buildscript {
    repositories {
        jcenter()
        google()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    } }/* buildscript {
repositories {
    mavenCentral()
    maven {
        url "https://oss.sonatype.org/content/repositories/snapshots/"
        url 'https://maven.google.com/'
        name 'Google'
    }
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
} }*/ allprojects {
apply plugin: "eclipse"
apply plugin: "idea"

version = '1.0'
ext {
    appName = 'Basketball'
    gdxVersion = '1.6.3'
    roboVMVersion = '1.4.0'
    box2DLightsVersion = '1.3'
    ashleyVersion = '1.4.0'
    aiVersion = '1.5.0'
}

repositories {
    mavenCentral()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
    maven { url "https://oss.sonatype.org/content/repositories/releases/" }

} } project(":desktop") {
apply plugin: "java"


dependencies {
    compile project(":core")
    compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
    compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
    compile "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
    compile "com.badlogicgames.gdx:gdx-tools:$gdxVersion"
} } project(":android") {
apply plugin: "android"

configurations { natives }

dependencies {
    compile project(":core")
    compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
    compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-armeabi-v7a"
    natives "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-x86"
    compile project(":BaseGameUtils")
    compile fileTree(dir: '../libs', include: '*.jar')
} } project(":core") {
apply plugin: "java"


dependencies {
    compile "com.badlogicgames.gdx:gdx:$gdxVersion"
    compile "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"
    compile fileTree(dir: '../libs', include: '*.jar')
} } tasks.eclipse.doLast {
delete ".project" } /*android {
compileSdkVersion 'Google Inc.:Google APIs:24' } dependencies { }*/

Can anyone please help me in this i am not getting any resolution on google as well.

ANSWER

Answered 2018-Mar-29 at 10:47

I had the same error and it could not seem to find the maven artifact "org.jetbrains.trove4j:trove4j:20160824".

There is no such one in maven central, but there is one in the jcenter repository: https://bintray.com/jetbrains/trove4j/trove4j

Add jcenter() to the repositories {} of your allprojects {} block and it should work.

Source https://stackoverflow.com/questions/48377700

QUESTION

Json representation not showing for newly added nested components

Asked 2018-Feb-15 at 09:27

Am creating a nested component inside another component, where am two-way binding the values of newly added fields Using JSON pipe in view, am not able to get the values as it is added dynamically

here is the plunker link, if you click on Add another address + link it will add two fields street and postcode, inside that there will be an add button, on click of that it will add DOB and Designation field, if you type any values it won't be showing in the below JSON view

Template

<div [formGroup]="adressForm">
    <div class="form-group col-xs-6">
        <label>street</label>
        <input type="text" class="form-control" formControlName="street">
        <small [hidden]="adressForm.controls.street.valid" class="text-danger">
            Street is required
        </small>
    </div> 
    <div class="form-group col-xs-6">
        <label>postcode</label> 
        <input type="text" class="form-control" formControlName="postcode">
    </div>
         <div class="margin-20">
          <a (click)="addextraField()" style="cursor: default">
            Add +
          </a>
        </div>

            <div formArrayName="extraspaces">
          <div *ngFor="let ext of adressForm.controls.extraspaces.controls; let i=index" class="panel panel-default">
            <div class="panel-heading">
              <span>Address {{i + 1}}</span>
              <span class="glyphicon glyphicon-remove pull-right" *ngIf="adressForm.controls.extraspaces.controls.length > 1" (click)="removeAddress(i)"></span>
            </div>
            <div class="panel-body" [formGroupName]="i">
              <extrafield [extragroup]="adressForm.controls.extraspaces.controls[i]"></extrafield>
            </div>
          </div>
        </div>

</div>

Component

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { Injectable } from '@angular/core';
@Component({
    moduleId: module.id,
    selector: 'address',
    templateUrl: 'address.component.html',
})
export class AddressComponent {
    @Input('group')
    public adressForm: FormGroup;
    private _fb: FormBuilder
    constructor(){}


    ngOnInit() {
        this.adressForm = this._fb.group({
            extraspaces: this._fb.array([])
        });

        // add address
        this.addextraField();

        /* subscribe to addresses value changes */
        // this.myForm.controls['addresses'].valueChanges.subscribe(x => {
        //   console.log(x);
        // })
    }


    initextraField() {
        return this._fb.group({
            dob: ['', Validators.required],
            designation: ['', Validators.required]
        });
    }

    addextraField() {
        const control = <FormArray>this.adressForm.controls['extraspaces'];
        const addrCtrl = this.initextraField();

        control.push(addrCtrl);
    }

    // removeAddress(i: number) {
    //     const control = <FormArray>this.myForm.controls['addresses'];
    //     control.removeAt(i);
    // }
}

please help me to resolve this issue, sorry if this is a duplicated one

ANSWER

Answered 2017-May-24 at 17:08

The only thing you need to remember is to always build the complete form in the parent, no matter if there is a grandchild like in your case. This way the parent is aware of the whole form and the changes you make to the form. So there is actually a really easy solution. Remove the following in your AddressComponent OnInit, since the parent will not be aware of this formgroup:

this.adressForm = this._fb.group({
   street: [''],
   postcode: [''],
   extraspaces: this._fb.array([])
});

why it seems that it would recognize street and postcode from this code, actually it doesn't, it recognizes these two, because you have set them in the parent function initAddress. So therefore, just add extraspaces: this._fb.array([]) in that function instead:

initAddress() {
    return this._fb.group({
        street: ['', Validators.required],
        postcode: [''],
        extraspaces: this._fb.array([])
    });
}

Here is your forked PLUNKER

EDIT:

I see you perhaps want to initialize also one of the innermost formgroup, then you could, then you could call function inside like so:

extraspaces: this._fb.array([this.initextraField()])

and use that same function (add it) in parent as you are using in AddressComponent, or then you manually set an empty form group inside that formArray.

Source https://stackoverflow.com/questions/44162215

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

VULNERABILITIES

No vulnerabilities reported

INSTALL ls.ext

You can use ls.ext like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the ls.ext component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

SUPPORT

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

Implement ls.ext faster with kandi.

  • Use the support, quality, security, license, reuse scores and reviewed functions to confirm the fit for your project.
  • Use the, Q & A, Installation and Support guides to implement faster.

Discover Millions of Libraries and
Pre-built Use Cases on kandi